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
134 char const * const known_coded_sizes[] = { "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};
204 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
205 /// them in ERT. "LaTeXe" must come before "LaTeX"!
206 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
207 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
208 int const known_phrase_lengths[] = {3, 5, 7, 0};
211 /// splits "x=z, y=b" into a map and an ordered keyword vector
212 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
217 keys.resize(v.size());
218 for (size_t i = 0; i < v.size(); ++i) {
219 size_t const pos = v[i].find('=');
220 string const index = trim(v[i].substr(0, pos));
221 string const value = trim(v[i].substr(pos + 1, string::npos));
229 * Split a LaTeX length into value and unit.
230 * The latter can be a real unit like "pt", or a latex length variable
231 * like "\textwidth". The unit may contain additional stuff like glue
232 * lengths, but we don't care, because such lengths are ERT anyway.
233 * \returns true if \p value and \p unit are valid.
235 bool splitLatexLength(string const & len, string & value, string & unit)
239 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
240 //'4,5' is a valid LaTeX length number. Change it to '4.5'
241 string const length = subst(len, ',', '.');
242 if (i == string::npos)
245 if (len[0] == '\\') {
246 // We had something like \textwidth without a factor
252 value = trim(string(length, 0, i));
256 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
257 if (contains(len, '\\'))
258 unit = trim(string(len, i));
260 unit = ascii_lowercase(trim(string(len, i)));
265 /// A simple function to translate a latex length to something LyX can
266 /// understand. Not perfect, but rather best-effort.
267 bool translate_len(string const & length, string & valstring, string & unit)
269 if (!splitLatexLength(length, valstring, unit))
271 // LyX uses percent values
273 istringstream iss(valstring);
278 string const percentval = oss.str();
280 if (unit.empty() || unit[0] != '\\')
282 string::size_type const i = unit.find(' ');
283 string const endlen = (i == string::npos) ? string() : string(unit, i);
284 if (unit == "\\textwidth") {
285 valstring = percentval;
286 unit = "text%" + endlen;
287 } else if (unit == "\\columnwidth") {
288 valstring = percentval;
289 unit = "col%" + endlen;
290 } else if (unit == "\\paperwidth") {
291 valstring = percentval;
292 unit = "page%" + endlen;
293 } else if (unit == "\\linewidth") {
294 valstring = percentval;
295 unit = "line%" + endlen;
296 } else if (unit == "\\paperheight") {
297 valstring = percentval;
298 unit = "pheight%" + endlen;
299 } else if (unit == "\\textheight") {
300 valstring = percentval;
301 unit = "theight%" + endlen;
309 string translate_len(string const & length)
313 if (translate_len(length, value, unit))
315 // If the input is invalid, return what we have.
323 * Translates a LaTeX length into \p value, \p unit and
324 * \p special parts suitable for a box inset.
325 * The difference from translate_len() is that a box inset knows about
326 * some special "units" that are stored in \p special.
328 void translate_box_len(string const & length, string & value, string & unit, string & special)
330 if (translate_len(length, value, unit)) {
331 if (unit == "\\height" || unit == "\\depth" ||
332 unit == "\\totalheight" || unit == "\\width") {
333 special = unit.substr(1);
334 // The unit is not used, but LyX requires a dummy setting
347 * Find a file with basename \p name in path \p path and an extension
350 string find_file(string const & name, string const & path,
351 char const * const * extensions)
353 for (char const * const * what = extensions; *what; ++what) {
354 string const trial = addExtension(name, *what);
355 if (makeAbsPath(trial, path).exists())
362 void begin_inset(ostream & os, string const & name)
364 os << "\n\\begin_inset " << name;
368 void begin_command_inset(ostream & os, string const & name,
369 string const & latexname)
371 begin_inset(os, "CommandInset ");
372 os << name << "\nLatexCommand " << latexname << '\n';
376 void end_inset(ostream & os)
378 os << "\n\\end_inset\n\n";
382 bool skip_braces(Parser & p)
384 if (p.next_token().cat() != catBegin)
387 if (p.next_token().cat() == catEnd) {
396 void handle_ert(ostream & os, string const & s, Context & context)
398 // We must have a valid layout before outputting the ERT inset.
399 context.check_layout(os);
400 Context newcontext(true, context.textclass);
401 begin_inset(os, "ERT");
402 os << "\nstatus collapsed\n";
403 newcontext.check_layout(os);
404 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
406 os << "\n\\backslash\n";
407 else if (*it == '\n') {
408 newcontext.new_paragraph(os);
409 newcontext.check_layout(os);
413 newcontext.check_end_layout(os);
418 void handle_comment(ostream & os, string const & s, Context & context)
420 // TODO: Handle this better
421 Context newcontext(true, context.textclass);
422 begin_inset(os, "ERT");
423 os << "\nstatus collapsed\n";
424 newcontext.check_layout(os);
425 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
427 os << "\n\\backslash\n";
431 // make sure that our comment is the last thing on the line
432 newcontext.new_paragraph(os);
433 newcontext.check_layout(os);
434 newcontext.check_end_layout(os);
439 Layout const * findLayout(TextClass const & textclass, string const & name)
441 DocumentClass::const_iterator lit = textclass.begin();
442 DocumentClass::const_iterator len = textclass.end();
443 for (; lit != len; ++lit)
444 if (lit->latexname() == name)
450 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
452 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
453 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
454 for (; it != en; ++it)
455 if (it->second.latexname() == name &&
456 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
457 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
458 return &(it->second);
463 void eat_whitespace(Parser &, ostream &, Context &, bool);
467 * Skips whitespace and braces.
468 * This should be called after a command has been parsed that is not put into
469 * ERT, and where LyX adds "{}" if needed.
471 void skip_spaces_braces(Parser & p, bool keepws = false)
473 /* The following four examples produce the same typeset output and
474 should be handled by this function:
482 // Unfortunately we need to skip comments, too.
483 // We can't use eat_whitespace since writing them after the {}
484 // results in different output in some cases.
485 bool const skipped_spaces = p.skip_spaces(true);
486 bool const skipped_braces = skip_braces(p);
487 if (keepws && skipped_spaces && !skipped_braces)
488 // put back the space (it is better handled by check_space)
489 p.unskip_spaces(true);
493 void output_command_layout(ostream & os, Parser & p, bool outer,
494 Context & parent_context,
495 Layout const * newlayout)
497 TeXFont const oldFont = parent_context.font;
498 // save the current font size
499 string const size = oldFont.size;
500 // reset the font size to default, because the font size switches
501 // don't affect section headings and the like
502 parent_context.font.size = Context::normalfont.size;
503 // we only need to write the font change if we have an open layout
504 if (!parent_context.atParagraphStart())
505 output_font_change(os, oldFont, parent_context.font);
506 parent_context.check_end_layout(os);
507 Context context(true, parent_context.textclass, newlayout,
508 parent_context.layout, parent_context.font);
509 if (parent_context.deeper_paragraph) {
510 // We are beginning a nested environment after a
511 // deeper paragraph inside the outer list environment.
512 // Therefore we don't need to output a "begin deeper".
513 context.need_end_deeper = true;
515 context.check_deeper(os);
516 context.check_layout(os);
517 unsigned int optargs = 0;
518 while (optargs < context.layout->optargs) {
519 eat_whitespace(p, os, context, false);
520 if (p.next_token().cat() == catEscape ||
521 p.next_token().character() != '[')
523 p.get_token(); // eat '['
524 begin_inset(os, "OptArg\n");
525 os << "status collapsed\n\n";
526 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
528 eat_whitespace(p, os, context, false);
531 unsigned int reqargs = 0;
532 while (LYX_FORMAT >= 392 && reqargs < context.layout->reqargs) {
533 eat_whitespace(p, os, context, false);
534 if (p.next_token().cat() != catBegin)
536 p.get_token(); // eat '{'
537 begin_inset(os, "OptArg\n");
538 os << "status collapsed\n\n";
539 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
541 eat_whitespace(p, os, context, false);
544 parse_text(p, os, FLAG_ITEM, outer, context);
545 context.check_end_layout(os);
546 if (parent_context.deeper_paragraph) {
547 // We must suppress the "end deeper" because we
548 // suppressed the "begin deeper" above.
549 context.need_end_deeper = false;
551 context.check_end_deeper(os);
552 // We don't need really a new paragraph, but
553 // we must make sure that the next item gets a \begin_layout.
554 parent_context.new_paragraph(os);
555 // Set the font size to the original value. No need to output it here
556 // (Context::begin_layout() will do that if needed)
557 parent_context.font.size = size;
562 * Output a space if necessary.
563 * This function gets called for every whitespace token.
565 * We have three cases here:
566 * 1. A space must be suppressed. Example: The lyxcode case below
567 * 2. A space may be suppressed. Example: Spaces before "\par"
568 * 3. A space must not be suppressed. Example: A space between two words
570 * We currently handle only 1. and 3 and from 2. only the case of
571 * spaces before newlines as a side effect.
573 * 2. could be used to suppress as many spaces as possible. This has two effects:
574 * - Reimporting LyX generated LaTeX files changes almost no whitespace
575 * - Superflous whitespace from non LyX generated LaTeX files is removed.
576 * The drawback is that the logic inside the function becomes
577 * complicated, and that is the reason why it is not implemented.
579 void check_space(Parser & p, ostream & os, Context & context)
581 Token const next = p.next_token();
582 Token const curr = p.curr_token();
583 // A space before a single newline and vice versa must be ignored
584 // LyX emits a newline before \end{lyxcode}.
585 // This newline must be ignored,
586 // otherwise LyX will add an additional protected space.
587 if (next.cat() == catSpace ||
588 next.cat() == catNewline ||
589 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
592 context.check_layout(os);
598 * Parse all arguments of \p command
600 void parse_arguments(string const & command,
601 vector<ArgumentType> const & template_arguments,
602 Parser & p, ostream & os, bool outer, Context & context)
604 string ert = command;
605 size_t no_arguments = template_arguments.size();
606 for (size_t i = 0; i < no_arguments; ++i) {
607 switch (template_arguments[i]) {
609 // This argument contains regular LaTeX
610 handle_ert(os, ert + '{', context);
611 eat_whitespace(p, os, context, false);
612 parse_text(p, os, FLAG_ITEM, outer, context);
616 // This argument consists only of a single item.
617 // The presence of '{' or not must be preserved.
619 if (p.next_token().cat() == catBegin)
620 ert += '{' + p.verbatim_item() + '}';
622 ert += p.verbatim_item();
625 // This argument may contain special characters
626 ert += '{' + p.verbatim_item() + '}';
629 // true because we must not eat whitespace
630 ert += p.getOpt(true);
634 handle_ert(os, ert, context);
639 * Check whether \p command is a known command. If yes,
640 * handle the command with all arguments.
641 * \return true if the command was parsed, false otherwise.
643 bool parse_command(string const & command, Parser & p, ostream & os,
644 bool outer, Context & context)
646 if (known_commands.find(command) != known_commands.end()) {
647 parse_arguments(command, known_commands[command], p, os,
655 /// Parses a minipage or parbox
656 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
657 Context & parent_context, bool use_parbox)
661 // We need to set the height to the LaTeX default of 1\\totalheight
662 // for the case when no height argument is given
663 string height_value = "1";
664 string height_unit = "in";
665 string height_special = "totalheight";
668 position = p.getArg('[', ']');
669 if (position != "t" && position != "c" && position != "b") {
671 cerr << "invalid position for minipage/parbox" << endl;
674 latex_height = p.getArg('[', ']');
675 translate_box_len(latex_height, height_value, height_unit, height_special);
678 inner_pos = p.getArg('[', ']');
679 if (inner_pos != "c" && inner_pos != "t" &&
680 inner_pos != "b" && inner_pos != "s") {
681 inner_pos = position;
682 cerr << "invalid inner_pos for minipage/parbox"
690 string const latex_width = p.verbatim_item();
691 translate_len(latex_width, width_value, width_unit);
692 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
693 // LyX can't handle length variables
698 ss << "\\begin{minipage}";
699 if (!position.empty())
700 ss << '[' << position << ']';
701 if (!latex_height.empty())
702 ss << '[' << latex_height << ']';
703 if (!inner_pos.empty())
704 ss << '[' << inner_pos << ']';
705 ss << "{" << latex_width << "}";
708 handle_ert(os, ss.str(), parent_context);
709 parent_context.new_paragraph(os);
710 parse_text_in_inset(p, os, flags, outer, parent_context);
712 handle_ert(os, "}", parent_context);
714 handle_ert(os, "\\end{minipage}", parent_context);
716 // LyX does not like empty positions, so we have
717 // to set them to the LaTeX default values here.
718 if (position.empty())
720 if (inner_pos.empty())
721 inner_pos = position;
722 parent_context.check_layout(os);
723 begin_inset(os, "Box Frameless\n");
724 os << "position \"" << position << "\"\n";
725 os << "hor_pos \"c\"\n";
726 os << "has_inner_box 1\n";
727 os << "inner_pos \"" << inner_pos << "\"\n";
728 os << "use_parbox " << use_parbox << "\n";
729 os << "width \"" << width_value << width_unit << "\"\n";
730 os << "special \"none\"\n";
731 os << "height \"" << height_value << height_unit << "\"\n";
732 os << "height_special \"" << height_special << "\"\n";
733 os << "status open\n\n";
734 parse_text_in_inset(p, os, flags, outer, parent_context);
736 #ifdef PRESERVE_LAYOUT
737 // LyX puts a % after the end of the minipage
738 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
740 //handle_comment(os, "%dummy", parent_context);
743 parent_context.new_paragraph(os);
745 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
746 //handle_comment(os, "%dummy", parent_context);
749 // We add a protected space if something real follows
750 if (p.good() && p.next_token().cat() != catComment) {
751 begin_inset(os, "space ~\n");
760 /// parse an unknown environment
761 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
762 unsigned flags, bool outer,
763 Context & parent_context)
765 if (name == "tabbing")
766 // We need to remember that we have to handle '\=' specially
767 flags |= FLAG_TABBING;
769 // We need to translate font changes and paragraphs inside the
770 // environment to ERT if we have a non standard font.
771 // Otherwise things like
772 // \large\begin{foo}\huge bar\end{foo}
774 bool const specialfont =
775 (parent_context.font != parent_context.normalfont);
776 bool const new_layout_allowed = parent_context.new_layout_allowed;
778 parent_context.new_layout_allowed = false;
779 handle_ert(os, "\\begin{" + name + "}", parent_context);
780 parse_text_snippet(p, os, flags, outer, parent_context);
781 handle_ert(os, "\\end{" + name + "}", parent_context);
783 parent_context.new_layout_allowed = new_layout_allowed;
787 void parse_environment(Parser & p, ostream & os, bool outer,
788 string & last_env, Context & parent_context)
790 Layout const * newlayout;
791 string const name = p.getArg('{', '}');
792 const bool is_starred = suffixIs(name, '*');
793 string const unstarred_name = rtrim(name, "*");
794 active_environments.push_back(name);
796 if (is_math_env(name)) {
797 parent_context.check_layout(os);
798 begin_inset(os, "Formula ");
799 os << "\\begin{" << name << "}";
800 parse_math(p, os, FLAG_END, MATH_MODE);
801 os << "\\end{" << name << "}";
805 else if (name == "tabular" || name == "longtable") {
806 eat_whitespace(p, os, parent_context, false);
807 parent_context.check_layout(os);
808 begin_inset(os, "Tabular ");
809 handle_tabular(p, os, name == "longtable", parent_context);
814 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
815 eat_whitespace(p, os, parent_context, false);
816 parent_context.check_layout(os);
817 begin_inset(os, "Float " + unstarred_name + "\n");
819 os << "placement " << p.getArg('[', ']') << '\n';
820 os << "wide " << convert<string>(is_starred)
821 << "\nsideways false"
822 << "\nstatus open\n\n";
823 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
825 // We don't need really a new paragraph, but
826 // we must make sure that the next item gets a \begin_layout.
827 parent_context.new_paragraph(os);
831 else if (name == "minipage") {
832 eat_whitespace(p, os, parent_context, false);
833 parse_box(p, os, FLAG_END, outer, parent_context, false);
837 else if (name == "comment") {
838 eat_whitespace(p, os, parent_context, false);
839 parent_context.check_layout(os);
840 begin_inset(os, "Note Comment\n");
841 os << "status open\n";
842 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
845 skip_braces(p); // eat {} that might by set by LyX behind comments
848 else if (name == "lyxgreyedout") {
849 eat_whitespace(p, os, parent_context, false);
850 parent_context.check_layout(os);
851 begin_inset(os, "Note Greyedout\n");
852 os << "status open\n";
853 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
858 else if (name == "framed" || name == "shaded") {
859 eat_whitespace(p, os, parent_context, false);
860 parent_context.check_layout(os);
861 if (name == "framed")
862 begin_inset(os, "Box Framed\n");
864 begin_inset(os, "Box Shaded\n");
865 os << "position \"t\"\n"
870 "width \"100col%\"\n"
873 "height_special \"totalheight\"\n"
875 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
880 else if (!parent_context.new_layout_allowed)
881 parse_unknown_environment(p, name, os, FLAG_END, outer,
884 // Alignment and spacing settings
885 // FIXME (bug xxxx): These settings can span multiple paragraphs and
886 // therefore are totally broken!
887 // Note that \centering, raggedright, and raggedleft cannot be handled, as
888 // they are commands not environments. They are furthermore switches that
889 // can be ended by another switches, but also by commands like \footnote or
890 // \parbox. So the only safe way is to leave them untouched.
891 else if (name == "center" || name == "centering" ||
892 name == "flushleft" || name == "flushright" ||
893 name == "singlespace" || name == "onehalfspace" ||
894 name == "doublespace" || name == "spacing") {
895 eat_whitespace(p, os, parent_context, false);
896 // We must begin a new paragraph if not already done
897 if (! parent_context.atParagraphStart()) {
898 parent_context.check_end_layout(os);
899 parent_context.new_paragraph(os);
901 if (name == "flushleft")
902 parent_context.add_extra_stuff("\\align left\n");
903 else if (name == "flushright")
904 parent_context.add_extra_stuff("\\align right\n");
905 else if (name == "center" || name == "centering")
906 parent_context.add_extra_stuff("\\align center\n");
907 else if (name == "singlespace")
908 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
909 else if (name == "onehalfspace")
910 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
911 else if (name == "doublespace")
912 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
913 else if (name == "spacing")
914 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
915 parse_text(p, os, FLAG_END, outer, parent_context);
916 // Just in case the environment is empty
917 parent_context.extra_stuff.erase();
918 // We must begin a new paragraph to reset the alignment
919 parent_context.new_paragraph(os);
923 // The single '=' is meant here.
924 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
925 newlayout->isEnvironment()) {
926 eat_whitespace(p, os, parent_context, false);
927 Context context(true, parent_context.textclass, newlayout,
928 parent_context.layout, parent_context.font);
929 if (parent_context.deeper_paragraph) {
930 // We are beginning a nested environment after a
931 // deeper paragraph inside the outer list environment.
932 // Therefore we don't need to output a "begin deeper".
933 context.need_end_deeper = true;
935 parent_context.check_end_layout(os);
936 if (last_env == name) {
937 // we need to output a separator since LyX would export
938 // the two environments as one otherwise (bug 5716)
939 docstring const sep = from_ascii("--Separator--");
940 TeX2LyXDocClass const & textclass(parent_context.textclass);
941 if (textclass.hasLayout(sep)) {
942 Context newcontext(parent_context);
943 newcontext.layout = &(textclass[sep]);
944 newcontext.check_layout(os);
945 newcontext.check_end_layout(os);
947 parent_context.check_layout(os);
948 begin_inset(os, "Note Note\n");
949 os << "status closed\n";
950 Context newcontext(true, textclass,
951 &(textclass.defaultLayout()));
952 newcontext.check_layout(os);
953 newcontext.check_end_layout(os);
955 parent_context.check_end_layout(os);
958 switch (context.layout->latextype) {
959 case LATEX_LIST_ENVIRONMENT:
960 context.add_par_extra_stuff("\\labelwidthstring "
961 + p.verbatim_item() + '\n');
964 case LATEX_BIB_ENVIRONMENT:
965 p.verbatim_item(); // swallow next arg
971 context.check_deeper(os);
972 parse_text(p, os, FLAG_END, outer, context);
973 context.check_end_layout(os);
974 if (parent_context.deeper_paragraph) {
975 // We must suppress the "end deeper" because we
976 // suppressed the "begin deeper" above.
977 context.need_end_deeper = false;
979 context.check_end_deeper(os);
980 parent_context.new_paragraph(os);
984 else if (name == "appendix") {
985 // This is no good latex style, but it works and is used in some documents...
986 eat_whitespace(p, os, parent_context, false);
987 parent_context.check_end_layout(os);
988 Context context(true, parent_context.textclass, parent_context.layout,
989 parent_context.layout, parent_context.font);
990 context.check_layout(os);
991 os << "\\start_of_appendix\n";
992 parse_text(p, os, FLAG_END, outer, context);
993 context.check_end_layout(os);
997 else if (known_environments.find(name) != known_environments.end()) {
998 vector<ArgumentType> arguments = known_environments[name];
999 // The last "argument" denotes wether we may translate the
1000 // environment contents to LyX
1001 // The default required if no argument is given makes us
1002 // compatible with the reLyXre environment.
1003 ArgumentType contents = arguments.empty() ?
1006 if (!arguments.empty())
1007 arguments.pop_back();
1008 // See comment in parse_unknown_environment()
1009 bool const specialfont =
1010 (parent_context.font != parent_context.normalfont);
1011 bool const new_layout_allowed =
1012 parent_context.new_layout_allowed;
1014 parent_context.new_layout_allowed = false;
1015 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1016 outer, parent_context);
1017 if (contents == verbatim)
1018 handle_ert(os, p.verbatimEnvironment(name),
1021 parse_text_snippet(p, os, FLAG_END, outer,
1023 handle_ert(os, "\\end{" + name + "}", parent_context);
1025 parent_context.new_layout_allowed = new_layout_allowed;
1029 parse_unknown_environment(p, name, os, FLAG_END, outer,
1033 active_environments.pop_back();
1037 /// parses a comment and outputs it to \p os.
1038 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1040 LASSERT(t.cat() == catComment, return);
1041 if (!t.cs().empty()) {
1042 context.check_layout(os);
1043 handle_comment(os, '%' + t.cs(), context);
1044 if (p.next_token().cat() == catNewline) {
1045 // A newline after a comment line starts a new
1047 if (context.new_layout_allowed) {
1048 if(!context.atParagraphStart())
1049 // Only start a new paragraph if not already
1050 // done (we might get called recursively)
1051 context.new_paragraph(os);
1053 handle_ert(os, "\n", context);
1054 eat_whitespace(p, os, context, true);
1057 // "%\n" combination
1064 * Reads spaces and comments until the first non-space, non-comment token.
1065 * New paragraphs (double newlines or \\par) are handled like simple spaces
1066 * if \p eatParagraph is true.
1067 * Spaces are skipped, but comments are written to \p os.
1069 void eat_whitespace(Parser & p, ostream & os, Context & context,
1073 Token const & t = p.get_token();
1074 if (t.cat() == catComment)
1075 parse_comment(p, os, t, context);
1076 else if ((! eatParagraph && p.isParagraph()) ||
1077 (t.cat() != catSpace && t.cat() != catNewline)) {
1086 * Set a font attribute, parse text and reset the font attribute.
1087 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1088 * \param currentvalue Current value of the attribute. Is set to the new
1089 * value during parsing.
1090 * \param newvalue New value of the attribute
1092 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1093 Context & context, string const & attribute,
1094 string & currentvalue, string const & newvalue)
1096 context.check_layout(os);
1097 string const oldvalue = currentvalue;
1098 currentvalue = newvalue;
1099 os << '\n' << attribute << ' ' << newvalue << "\n";
1100 parse_text_snippet(p, os, flags, outer, context);
1101 context.check_layout(os);
1102 os << '\n' << attribute << ' ' << oldvalue << "\n";
1103 currentvalue = oldvalue;
1107 /// get the arguments of a natbib or jurabib citation command
1108 void get_cite_arguments(Parser & p, bool natbibOrder,
1109 string & before, string & after)
1111 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1113 // text before the citation
1115 // text after the citation
1116 after = p.getFullOpt();
1118 if (!after.empty()) {
1119 before = p.getFullOpt();
1120 if (natbibOrder && !before.empty())
1121 swap(before, after);
1126 /// Convert filenames with TeX macros and/or quotes to something LyX
1128 string const normalize_filename(string const & name)
1130 Parser p(trim(name, "\""));
1133 Token const & t = p.get_token();
1134 if (t.cat() != catEscape)
1136 else if (t.cs() == "lyxdot") {
1137 // This is used by LyX for simple dots in relative
1141 } else if (t.cs() == "space") {
1151 /// Convert \p name from TeX convention (relative to master file) to LyX
1152 /// convention (relative to .lyx file) if it is relative
1153 void fix_relative_filename(string & name)
1155 if (FileName::isAbsolute(name))
1158 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1159 from_utf8(getParentFilePath())));
1163 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1164 void parse_noweb(Parser & p, ostream & os, Context & context)
1166 // assemble the rest of the keyword
1170 Token const & t = p.get_token();
1171 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1174 scrap = (p.good() && p.next_token().asInput() == "=");
1176 name += p.get_token().asInput();
1179 name += t.asInput();
1182 if (!scrap || !context.new_layout_allowed ||
1183 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1184 cerr << "Warning: Could not interpret '" << name
1185 << "'. Ignoring it." << endl;
1189 // We use new_paragraph instead of check_end_layout because the stuff
1190 // following the noweb chunk needs to start with a \begin_layout.
1191 // This may create a new paragraph even if there was none in the
1192 // noweb file, but the alternative is an invalid LyX file. Since
1193 // noweb code chunks are implemented with a layout style in LyX they
1194 // always must be in an own paragraph.
1195 context.new_paragraph(os);
1196 Context newcontext(true, context.textclass,
1197 &context.textclass[from_ascii("Scrap")]);
1198 newcontext.check_layout(os);
1201 Token const & t = p.get_token();
1202 // We abuse the parser a bit, because this is no TeX syntax
1204 if (t.cat() == catEscape)
1205 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1208 begin_inset(oss, "Newline newline");
1210 os << subst(t.asInput(), "\n", oss.str());
1212 // The scrap chunk is ended by an @ at the beginning of a line.
1213 // After the @ the line may contain a comment and/or
1214 // whitespace, but nothing else.
1215 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1216 (p.next_token().cat() == catSpace ||
1217 p.next_token().cat() == catNewline ||
1218 p.next_token().cat() == catComment)) {
1219 while (p.good() && p.next_token().cat() == catSpace)
1220 os << p.get_token().asInput();
1221 if (p.next_token().cat() == catComment)
1222 // The comment includes a final '\n'
1223 os << p.get_token().asInput();
1225 if (p.next_token().cat() == catNewline)
1232 newcontext.check_end_layout(os);
1236 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1237 bool is_macro(Parser & p)
1239 Token first = p.curr_token();
1240 if (first.cat() != catEscape || !p.good())
1242 if (first.cs() == "def")
1244 if (first.cs() != "global" && first.cs() != "long")
1246 Token second = p.get_token();
1248 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1249 second.cat() == catNewline || second.cat() == catComment)) {
1250 second = p.get_token();
1253 bool secondvalid = second.cat() == catEscape;
1255 bool thirdvalid = false;
1256 if (p.good() && first.cs() == "global" && secondvalid &&
1257 second.cs() == "long") {
1258 third = p.get_token();
1260 while (p.good() && !p.isParagraph() &&
1261 (third.cat() == catSpace ||
1262 third.cat() == catNewline ||
1263 third.cat() == catComment)) {
1264 third = p.get_token();
1267 thirdvalid = third.cat() == catEscape;
1269 for (int i = 0; i < pos; ++i)
1274 return (first.cs() == "global" || first.cs() == "long") &&
1275 second.cs() == "def";
1276 return first.cs() == "global" && second.cs() == "long" &&
1277 third.cs() == "def";
1281 /// Parse a macro definition (assumes that is_macro() returned true)
1282 void parse_macro(Parser & p, ostream & os, Context & context)
1284 context.check_layout(os);
1285 Token first = p.curr_token();
1288 string command = first.asInput();
1289 if (first.cs() != "def") {
1291 eat_whitespace(p, os, context, false);
1292 second = p.curr_token();
1293 command += second.asInput();
1294 if (second.cs() != "def") {
1296 eat_whitespace(p, os, context, false);
1297 third = p.curr_token();
1298 command += third.asInput();
1301 eat_whitespace(p, os, context, false);
1302 string const name = p.get_token().cs();
1303 eat_whitespace(p, os, context, false);
1309 while (p.next_token().cat() != catBegin) {
1310 if (p.next_token().cat() == catParameter) {
1315 // followed by number?
1316 if (p.next_token().cat() == catOther) {
1317 char c = p.getChar();
1319 // number = current arity + 1?
1320 if (c == arity + '0' + 1)
1325 paramtext += p.get_token().cs();
1327 paramtext += p.get_token().cs();
1332 // only output simple (i.e. compatible) macro as FormulaMacros
1333 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1335 context.check_layout(os);
1336 begin_inset(os, "FormulaMacro");
1337 os << "\n\\def" << ert;
1340 handle_ert(os, command + ert, context);
1343 } // anonymous namespace
1346 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1349 Layout const * newlayout = 0;
1350 InsetLayout const * newinsetlayout = 0;
1351 // Store the latest bibliographystyle and nocite{*} option
1352 // (needed for bibtex inset)
1354 string bibliographystyle;
1355 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1356 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1359 Token const & t = p.get_token();
1362 debugToken(cerr, t, flags);
1365 if (flags & FLAG_ITEM) {
1366 if (t.cat() == catSpace)
1369 flags &= ~FLAG_ITEM;
1370 if (t.cat() == catBegin) {
1371 // skip the brace and collect everything to the next matching
1373 flags |= FLAG_BRACE_LAST;
1377 // handle only this single token, leave the loop if done
1378 flags |= FLAG_LEAVE;
1381 if (t.cat() != catEscape && t.character() == ']' &&
1382 (flags & FLAG_BRACK_LAST))
1384 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1387 // If there is anything between \end{env} and \begin{env} we
1388 // don't need to output a separator.
1389 if (t.cat() != catSpace && t.cat() != catNewline &&
1390 t.asInput() != "\\begin")
1396 if (t.cat() == catMath) {
1397 // we are inside some text mode thingy, so opening new math is allowed
1398 context.check_layout(os);
1399 begin_inset(os, "Formula ");
1400 Token const & n = p.get_token();
1401 if (n.cat() == catMath && outer) {
1402 // TeX's $$...$$ syntax for displayed math
1404 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1406 p.get_token(); // skip the second '$' token
1408 // simple $...$ stuff
1411 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1417 else if (t.cat() == catSuper || t.cat() == catSub)
1418 cerr << "catcode " << t << " illegal in text mode\n";
1420 // Basic support for english quotes. This should be
1421 // extended to other quotes, but is not so easy (a
1422 // left english quote is the same as a right german
1424 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1425 context.check_layout(os);
1426 begin_inset(os, "Quotes ");
1432 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1433 context.check_layout(os);
1434 begin_inset(os, "Quotes ");
1441 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1442 context.check_layout(os);
1443 begin_inset(os, "Quotes ");
1450 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1451 context.check_layout(os);
1452 begin_inset(os, "Quotes ");
1459 else if (t.asInput() == "<"
1460 && p.next_token().asInput() == "<" && noweb_mode) {
1462 parse_noweb(p, os, context);
1465 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1466 check_space(p, os, context);
1468 else if (t.character() == '[' && noweb_mode &&
1469 p.next_token().character() == '[') {
1470 // These can contain underscores
1472 string const s = p.getFullOpt() + ']';
1473 if (p.next_token().character() == ']')
1476 cerr << "Warning: Inserting missing ']' in '"
1477 << s << "'." << endl;
1478 handle_ert(os, s, context);
1481 else if (t.cat() == catLetter) {
1482 context.check_layout(os);
1483 // Workaround for bug 4752.
1484 // FIXME: This whole code block needs to be removed
1485 // when the bug is fixed and tex2lyx produces
1486 // the updated file format.
1487 // The replacement algorithm in LyX is so stupid that
1488 // it even translates a phrase if it is part of a word.
1489 bool handled = false;
1490 for (int const * l = known_phrase_lengths; *l; ++l) {
1491 string phrase = t.cs();
1492 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1493 phrase += p.get_token().cs();
1494 if (is_known(phrase, known_coded_phrases)) {
1495 handle_ert(os, phrase, context);
1499 for (size_t i = 1; i < phrase.length(); ++i)
1507 else if (t.cat() == catOther ||
1508 t.cat() == catAlign ||
1509 t.cat() == catParameter) {
1510 // This translates "&" to "\\&" which may be wrong...
1511 context.check_layout(os);
1515 else if (p.isParagraph()) {
1516 if (context.new_layout_allowed)
1517 context.new_paragraph(os);
1519 handle_ert(os, "\\par ", context);
1520 eat_whitespace(p, os, context, true);
1523 else if (t.cat() == catActive) {
1524 context.check_layout(os);
1525 if (t.character() == '~') {
1526 if (context.layout->free_spacing)
1529 begin_inset(os, "space ~\n");
1536 else if (t.cat() == catBegin &&
1537 p.next_token().cat() == catEnd) {
1539 Token const prev = p.prev_token();
1541 if (p.next_token().character() == '`' ||
1542 (prev.character() == '-' &&
1543 p.next_token().character() == '-'))
1544 ; // ignore it in {}`` or -{}-
1546 handle_ert(os, "{}", context);
1550 else if (t.cat() == catBegin) {
1551 context.check_layout(os);
1552 // special handling of font attribute changes
1553 Token const prev = p.prev_token();
1554 Token const next = p.next_token();
1555 TeXFont const oldFont = context.font;
1556 if (next.character() == '[' ||
1557 next.character() == ']' ||
1558 next.character() == '*') {
1560 if (p.next_token().cat() == catEnd) {
1565 handle_ert(os, "{", context);
1566 parse_text_snippet(p, os,
1569 handle_ert(os, "}", context);
1571 } else if (! context.new_layout_allowed) {
1572 handle_ert(os, "{", context);
1573 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1575 handle_ert(os, "}", context);
1576 } else if (is_known(next.cs(), known_sizes)) {
1577 // next will change the size, so we must
1579 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1581 if (!context.atParagraphStart())
1583 << context.font.size << "\n";
1584 } else if (is_known(next.cs(), known_font_families)) {
1585 // next will change the font family, so we
1586 // must reset it here
1587 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1589 if (!context.atParagraphStart())
1591 << context.font.family << "\n";
1592 } else if (is_known(next.cs(), known_font_series)) {
1593 // next will change the font series, so we
1594 // must reset it here
1595 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1597 if (!context.atParagraphStart())
1599 << context.font.series << "\n";
1600 } else if (is_known(next.cs(), known_font_shapes)) {
1601 // next will change the font shape, so we
1602 // must reset it here
1603 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1605 if (!context.atParagraphStart())
1607 << context.font.shape << "\n";
1608 } else if (is_known(next.cs(), known_old_font_families) ||
1609 is_known(next.cs(), known_old_font_series) ||
1610 is_known(next.cs(), known_old_font_shapes)) {
1611 // next will change the font family, series
1612 // and shape, so we must reset it here
1613 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1615 if (!context.atParagraphStart())
1617 << context.font.family
1619 << context.font.series
1621 << context.font.shape << "\n";
1623 handle_ert(os, "{", context);
1624 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1626 handle_ert(os, "}", context);
1630 else if (t.cat() == catEnd) {
1631 if (flags & FLAG_BRACE_LAST) {
1634 cerr << "stray '}' in text\n";
1635 handle_ert(os, "}", context);
1638 else if (t.cat() == catComment)
1639 parse_comment(p, os, t, context);
1642 // control sequences
1645 else if (t.cs() == "(") {
1646 context.check_layout(os);
1647 begin_inset(os, "Formula");
1649 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1654 else if (t.cs() == "[") {
1655 context.check_layout(os);
1656 begin_inset(os, "Formula");
1658 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1663 else if (t.cs() == "begin")
1664 parse_environment(p, os, outer, last_env, context);
1666 else if (t.cs() == "end") {
1667 if (flags & FLAG_END) {
1668 // eat environment name
1669 string const name = p.getArg('{', '}');
1670 if (name != active_environment())
1671 cerr << "\\end{" + name + "} does not match \\begin{"
1672 + active_environment() + "}\n";
1675 p.error("found 'end' unexpectedly");
1678 else if (t.cs() == "item") {
1681 bool optarg = false;
1682 if (p.next_token().cat() != catEscape &&
1683 p.next_token().character() == '[') {
1684 p.get_token(); // eat '['
1685 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1690 context.check_layout(os);
1691 if (context.has_item) {
1692 // An item in an unknown list-like environment
1693 // FIXME: Do this in check_layout()!
1694 context.has_item = false;
1696 handle_ert(os, "\\item", context);
1698 handle_ert(os, "\\item ", context);
1701 if (context.layout->labeltype != LABEL_MANUAL) {
1702 // LyX does not support \item[\mybullet]
1703 // in itemize environments
1704 handle_ert(os, "[", context);
1706 handle_ert(os, "]", context);
1707 } else if (!s.empty()) {
1708 // The space is needed to separate the
1709 // item from the rest of the sentence.
1711 eat_whitespace(p, os, context, false);
1716 else if (t.cs() == "bibitem") {
1718 context.check_layout(os);
1719 begin_command_inset(os, "bibitem", "bibitem");
1720 os << "label \"" << p.getOptContent() << "\"\n";
1721 os << "key \"" << p.verbatim_item() << "\"\n";
1725 else if (is_macro(p))
1726 parse_macro(p, os, context);
1728 else if (t.cs() == "noindent") {
1730 context.add_par_extra_stuff("\\noindent\n");
1733 else if (t.cs() == "appendix") {
1734 context.add_par_extra_stuff("\\start_of_appendix\n");
1735 // We need to start a new paragraph. Otherwise the
1736 // appendix in 'bla\appendix\chapter{' would start
1738 context.new_paragraph(os);
1739 // We need to make sure that the paragraph is
1740 // generated even if it is empty. Otherwise the
1741 // appendix in '\par\appendix\par\chapter{' would
1743 context.check_layout(os);
1744 // FIXME: This is a hack to prevent paragraph
1745 // deletion if it is empty. Handle this better!
1747 "%dummy comment inserted by tex2lyx to "
1748 "ensure that this paragraph is not empty",
1750 // Both measures above may generate an additional
1751 // empty paragraph, but that does not hurt, because
1752 // whitespace does not matter here.
1753 eat_whitespace(p, os, context, true);
1756 // Starred section headings
1757 // Must attempt to parse "Section*" before "Section".
1758 else if ((p.next_token().asInput() == "*") &&
1759 context.new_layout_allowed &&
1760 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1761 newlayout->isCommand()) {
1764 output_command_layout(os, p, outer, context, newlayout);
1768 // Section headings and the like
1769 else if (context.new_layout_allowed &&
1770 (newlayout = findLayout(context.textclass, t.cs())) &&
1771 newlayout->isCommand()) {
1773 output_command_layout(os, p, outer, context, newlayout);
1777 else if (t.cs() == "caption") {
1779 context.check_layout(os);
1781 begin_inset(os, "Caption\n\n");
1782 Context newcontext(true, context.textclass);
1783 newcontext.font = context.font;
1784 newcontext.check_layout(os);
1785 if (p.next_token().cat() != catEscape &&
1786 p.next_token().character() == '[') {
1787 p.get_token(); // eat '['
1788 begin_inset(os, "OptArg\n");
1789 os << "status collapsed\n";
1790 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1792 eat_whitespace(p, os, context, false);
1794 parse_text(p, os, FLAG_ITEM, outer, context);
1795 context.check_end_layout(os);
1796 // We don't need really a new paragraph, but
1797 // we must make sure that the next item gets a \begin_layout.
1798 context.new_paragraph(os);
1801 newcontext.check_end_layout(os);
1804 else if (t.cs() == "includegraphics") {
1805 bool const clip = p.next_token().asInput() == "*";
1808 string const arg = p.getArg('[', ']');
1809 map<string, string> opts;
1810 vector<string> keys;
1811 split_map(arg, opts, keys);
1813 opts["clip"] = string();
1814 string name = normalize_filename(p.verbatim_item());
1816 string const path = getMasterFilePath();
1817 // We want to preserve relative / absolute filenames,
1818 // therefore path is only used for testing
1819 if (!makeAbsPath(name, path).exists()) {
1820 // The file extension is probably missing.
1821 // Now try to find it out.
1822 string const dvips_name =
1823 find_file(name, path,
1824 known_dvips_graphics_formats);
1825 string const pdftex_name =
1826 find_file(name, path,
1827 known_pdftex_graphics_formats);
1828 if (!dvips_name.empty()) {
1829 if (!pdftex_name.empty()) {
1830 cerr << "This file contains the "
1832 "\"\\includegraphics{"
1834 "However, files\n\""
1835 << dvips_name << "\" and\n\""
1836 << pdftex_name << "\"\n"
1837 "both exist, so I had to make a "
1838 "choice and took the first one.\n"
1839 "Please move the unwanted one "
1840 "someplace else and try again\n"
1841 "if my choice was wrong."
1845 } else if (!pdftex_name.empty()) {
1851 if (makeAbsPath(name, path).exists())
1852 fix_relative_filename(name);
1854 cerr << "Warning: Could not find graphics file '"
1855 << name << "'." << endl;
1857 context.check_layout(os);
1858 begin_inset(os, "Graphics ");
1859 os << "\n\tfilename " << name << '\n';
1860 if (opts.find("width") != opts.end())
1862 << translate_len(opts["width"]) << '\n';
1863 if (opts.find("height") != opts.end())
1865 << translate_len(opts["height"]) << '\n';
1866 if (opts.find("scale") != opts.end()) {
1867 istringstream iss(opts["scale"]);
1871 os << "\tscale " << val << '\n';
1873 if (opts.find("angle") != opts.end()) {
1874 os << "\trotateAngle "
1875 << opts["angle"] << '\n';
1876 vector<string>::const_iterator a =
1877 find(keys.begin(), keys.end(), "angle");
1878 vector<string>::const_iterator s =
1879 find(keys.begin(), keys.end(), "width");
1880 if (s == keys.end())
1881 s = find(keys.begin(), keys.end(), "height");
1882 if (s == keys.end())
1883 s = find(keys.begin(), keys.end(), "scale");
1884 if (s != keys.end() && distance(s, a) > 0)
1885 os << "\tscaleBeforeRotation\n";
1887 if (opts.find("origin") != opts.end()) {
1889 string const opt = opts["origin"];
1890 if (opt.find('l') != string::npos) ss << "left";
1891 if (opt.find('r') != string::npos) ss << "right";
1892 if (opt.find('c') != string::npos) ss << "center";
1893 if (opt.find('t') != string::npos) ss << "Top";
1894 if (opt.find('b') != string::npos) ss << "Bottom";
1895 if (opt.find('B') != string::npos) ss << "Baseline";
1896 if (!ss.str().empty())
1897 os << "\trotateOrigin " << ss.str() << '\n';
1899 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1901 if (opts.find("keepaspectratio") != opts.end())
1902 os << "\tkeepAspectRatio\n";
1903 if (opts.find("clip") != opts.end())
1905 if (opts.find("draft") != opts.end())
1907 if (opts.find("bb") != opts.end())
1908 os << "\tBoundingBox "
1909 << opts["bb"] << '\n';
1910 int numberOfbbOptions = 0;
1911 if (opts.find("bbllx") != opts.end())
1912 numberOfbbOptions++;
1913 if (opts.find("bblly") != opts.end())
1914 numberOfbbOptions++;
1915 if (opts.find("bburx") != opts.end())
1916 numberOfbbOptions++;
1917 if (opts.find("bbury") != opts.end())
1918 numberOfbbOptions++;
1919 if (numberOfbbOptions == 4)
1920 os << "\tBoundingBox "
1921 << opts["bbllx"] << " " << opts["bblly"] << " "
1922 << opts["bburx"] << " " << opts["bbury"] << '\n';
1923 else if (numberOfbbOptions > 0)
1924 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1925 numberOfbbOptions = 0;
1926 if (opts.find("natwidth") != opts.end())
1927 numberOfbbOptions++;
1928 if (opts.find("natheight") != opts.end())
1929 numberOfbbOptions++;
1930 if (numberOfbbOptions == 2)
1931 os << "\tBoundingBox 0bp 0bp "
1932 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1933 else if (numberOfbbOptions > 0)
1934 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1935 ostringstream special;
1936 if (opts.find("hiresbb") != opts.end())
1937 special << "hiresbb,";
1938 if (opts.find("trim") != opts.end())
1940 if (opts.find("viewport") != opts.end())
1941 special << "viewport=" << opts["viewport"] << ',';
1942 if (opts.find("totalheight") != opts.end())
1943 special << "totalheight=" << opts["totalheight"] << ',';
1944 if (opts.find("type") != opts.end())
1945 special << "type=" << opts["type"] << ',';
1946 if (opts.find("ext") != opts.end())
1947 special << "ext=" << opts["ext"] << ',';
1948 if (opts.find("read") != opts.end())
1949 special << "read=" << opts["read"] << ',';
1950 if (opts.find("command") != opts.end())
1951 special << "command=" << opts["command"] << ',';
1952 string s_special = special.str();
1953 if (!s_special.empty()) {
1954 // We had special arguments. Remove the trailing ','.
1955 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1957 // TODO: Handle the unknown settings better.
1958 // Warn about invalid options.
1959 // Check whether some option was given twice.
1963 else if (t.cs() == "footnote" ||
1964 (t.cs() == "thanks" && context.layout->intitle)) {
1966 context.check_layout(os);
1967 begin_inset(os, "Foot\n");
1968 os << "status collapsed\n\n";
1969 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1973 else if (t.cs() == "marginpar") {
1975 context.check_layout(os);
1976 begin_inset(os, "Marginal\n");
1977 os << "status collapsed\n\n";
1978 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1982 else if (t.cs() == "ensuremath") {
1984 context.check_layout(os);
1985 string const s = p.verbatim_item();
1986 //FIXME: this never triggers in UTF8
1987 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1990 handle_ert(os, "\\ensuremath{" + s + "}",
1994 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1995 // FIXME: Somehow prevent title layouts if
1996 // "maketitle" was not found
1998 skip_spaces_braces(p);
2001 else if (t.cs() == "tableofcontents") {
2002 context.check_layout(os);
2003 begin_command_inset(os, "toc", "tableofcontents");
2005 skip_spaces_braces(p);
2008 else if (t.cs() == "listoffigures") {
2009 context.check_layout(os);
2010 begin_inset(os, "FloatList figure\n");
2012 skip_spaces_braces(p);
2015 else if (t.cs() == "listoftables") {
2016 context.check_layout(os);
2017 begin_inset(os, "FloatList table\n");
2019 skip_spaces_braces(p);
2022 else if (t.cs() == "listof") {
2023 p.skip_spaces(true);
2024 string const name = p.get_token().cs();
2025 if (context.textclass.floats().typeExist(name)) {
2026 context.check_layout(os);
2027 begin_inset(os, "FloatList ");
2030 p.get_token(); // swallow second arg
2032 handle_ert(os, "\\listof{" + name + "}", context);
2035 else if (t.cs() == "textrm")
2036 parse_text_attributes(p, os, FLAG_ITEM, outer,
2037 context, "\\family",
2038 context.font.family, "roman");
2040 else if (t.cs() == "textsf")
2041 parse_text_attributes(p, os, FLAG_ITEM, outer,
2042 context, "\\family",
2043 context.font.family, "sans");
2045 else if (t.cs() == "texttt")
2046 parse_text_attributes(p, os, FLAG_ITEM, outer,
2047 context, "\\family",
2048 context.font.family, "typewriter");
2050 else if (t.cs() == "textmd")
2051 parse_text_attributes(p, os, FLAG_ITEM, outer,
2052 context, "\\series",
2053 context.font.series, "medium");
2055 else if (t.cs() == "textbf")
2056 parse_text_attributes(p, os, FLAG_ITEM, outer,
2057 context, "\\series",
2058 context.font.series, "bold");
2060 else if (t.cs() == "textup")
2061 parse_text_attributes(p, os, FLAG_ITEM, outer,
2063 context.font.shape, "up");
2065 else if (t.cs() == "textit")
2066 parse_text_attributes(p, os, FLAG_ITEM, outer,
2068 context.font.shape, "italic");
2070 else if (t.cs() == "textsl")
2071 parse_text_attributes(p, os, FLAG_ITEM, outer,
2073 context.font.shape, "slanted");
2075 else if (t.cs() == "textsc")
2076 parse_text_attributes(p, os, FLAG_ITEM, outer,
2078 context.font.shape, "smallcaps");
2080 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2081 context.check_layout(os);
2082 TeXFont oldFont = context.font;
2083 context.font.init();
2084 context.font.size = oldFont.size;
2085 os << "\n\\family " << context.font.family << "\n";
2086 os << "\n\\series " << context.font.series << "\n";
2087 os << "\n\\shape " << context.font.shape << "\n";
2088 if (t.cs() == "textnormal") {
2089 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2090 output_font_change(os, context.font, oldFont);
2091 context.font = oldFont;
2093 eat_whitespace(p, os, context, false);
2096 else if (t.cs() == "textcolor") {
2097 // scheme is \textcolor{color name}{text}
2098 string const color = p.verbatim_item();
2099 // we only support the predefined colors of the color package
2100 if (color == "black" || color == "blue" || color == "cyan"
2101 || color == "green" || color == "magenta" || color == "red"
2102 || color == "white" || color == "yellow") {
2103 context.check_layout(os);
2104 os << "\n\\color " << color << "\n";
2105 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2106 context.check_layout(os);
2107 os << "\n\\color inherit\n";
2109 // for custom defined colors
2110 handle_ert(os, t.asInput() + "{" + color + "}", context);
2113 else if (t.cs() == "underbar") {
2114 // Do NOT handle \underline.
2115 // \underbar cuts through y, g, q, p etc.,
2116 // \underline does not.
2117 context.check_layout(os);
2118 os << "\n\\bar under\n";
2119 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2120 context.check_layout(os);
2121 os << "\n\\bar default\n";
2124 else if (t.cs() == "emph" || t.cs() == "noun") {
2125 context.check_layout(os);
2126 os << "\n\\" << t.cs() << " on\n";
2127 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2128 context.check_layout(os);
2129 os << "\n\\" << t.cs() << " default\n";
2132 else if (t.cs() == "lyxline") {
2133 context.check_layout(os);
2137 else if (is_known(t.cs(), known_phrases)) {
2138 // FIXME: This needs to be changed when bug 4752 is fixed.
2139 char const * const * where = is_known(t.cs(), known_phrases);
2140 context.check_layout(os);
2141 os << known_coded_phrases[where - known_phrases];
2142 skip_spaces_braces(p);
2145 else if (is_known(t.cs(), known_ref_commands)) {
2146 context.check_layout(os);
2147 begin_command_inset(os, "ref", t.cs());
2148 // LyX cannot handle newlines in a latex command
2149 // FIXME: Move the substitution into parser::getOpt()?
2150 os << subst(p.getOpt(), "\n", " ");
2151 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2155 else if (use_natbib &&
2156 is_known(t.cs(), known_natbib_commands) &&
2157 ((t.cs() != "citefullauthor" &&
2158 t.cs() != "citeyear" &&
2159 t.cs() != "citeyearpar") ||
2160 p.next_token().asInput() != "*")) {
2161 context.check_layout(os);
2162 string command = t.cs();
2163 if (p.next_token().asInput() == "*") {
2167 if (command == "citefullauthor")
2168 // alternative name for "\\citeauthor*"
2169 command = "citeauthor*";
2171 // text before the citation
2173 // text after the citation
2175 get_cite_arguments(p, true, before, after);
2177 if (command == "cite") {
2178 // \cite without optional argument means
2179 // \citet, \cite with at least one optional
2180 // argument means \citep.
2181 if (before.empty() && after.empty())
2186 if (before.empty() && after == "[]")
2187 // avoid \citet[]{a}
2189 else if (before == "[]" && after == "[]") {
2190 // avoid \citet[][]{a}
2194 // remove the brackets around after and before
2195 if (!after.empty()) {
2197 after.erase(after.length() - 1, 1);
2198 // LyX cannot handle newlines in the parameter
2199 after = subst(after, "\n", " ");
2201 if (!before.empty()) {
2203 before.erase(before.length() - 1, 1);
2204 // LyX cannot handle newlines in the parameter
2205 before = subst(before, "\n", " ");
2207 begin_command_inset(os, "citation", command);
2208 os << "after " << '"' << after << '"' << "\n";
2209 os << "before " << '"' << before << '"' << "\n";
2210 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2214 else if (use_jurabib &&
2215 is_known(t.cs(), known_jurabib_commands) &&
2216 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2217 context.check_layout(os);
2218 string command = t.cs();
2219 if (p.next_token().asInput() == "*") {
2223 char argumentOrder = '\0';
2224 vector<string> const & options = used_packages["jurabib"];
2225 if (find(options.begin(), options.end(),
2226 "natbiborder") != options.end())
2227 argumentOrder = 'n';
2228 else if (find(options.begin(), options.end(),
2229 "jurabiborder") != options.end())
2230 argumentOrder = 'j';
2232 // text before the citation
2234 // text after the citation
2236 get_cite_arguments(p, argumentOrder != 'j', before, after);
2238 string const citation = p.verbatim_item();
2239 if (!before.empty() && argumentOrder == '\0') {
2240 cerr << "Warning: Assuming argument order "
2241 "of jurabib version 0.6 for\n'"
2242 << command << before << after << '{'
2243 << citation << "}'.\n"
2244 "Add 'jurabiborder' to the jurabib "
2245 "package options if you used an\n"
2246 "earlier jurabib version." << endl;
2248 if (!after.empty()) {
2250 after.erase(after.length() - 1, 1);
2252 if (!before.empty()) {
2254 before.erase(before.length() - 1, 1);
2256 begin_command_inset(os, "citation", command);
2257 os << "after " << '"' << after << '"' << "\n";
2258 os << "before " << '"' << before << '"' << "\n";
2259 os << "key " << '"' << citation << '"' << "\n";
2263 else if (t.cs() == "cite"
2264 || t.cs() == "nocite") {
2265 context.check_layout(os);
2266 // LyX cannot handle newlines in a latex command
2267 string after = subst(p.getOptContent(), "\n", " ");
2268 string key = subst(p.verbatim_item(), "\n", " ");
2269 // store the case that it is "\nocite{*}" to use it later for
2272 begin_command_inset(os, "citation", t.cs());
2273 os << "after " << '"' << after << '"' << "\n";
2274 os << "key " << '"' << key << '"' << "\n";
2276 } else if (t.cs() == "nocite")
2280 else if (t.cs() == "index") {
2281 context.check_layout(os);
2282 begin_inset(os, "Index\n");
2283 os << "status collapsed\n";
2284 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2288 else if (t.cs() == "nomenclature") {
2289 context.check_layout(os);
2290 begin_command_inset(os, "nomenclature", "nomenclature");
2291 // LyX cannot handle newlines in a latex command
2292 string prefix = subst(p.getOptContent(), "\n", " ");
2293 if (!prefix.empty())
2294 os << "prefix " << '"' << prefix << '"' << "\n";
2295 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2296 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2300 else if (t.cs() == "label") {
2301 context.check_layout(os);
2302 begin_command_inset(os, "label", "label");
2303 // LyX cannot handle newlines in a latex command
2304 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2308 else if (t.cs() == "printindex") {
2309 context.check_layout(os);
2310 begin_command_inset(os, "index_print", "printindex");
2312 skip_spaces_braces(p);
2315 else if (t.cs() == "printnomenclature") {
2316 context.check_layout(os);
2317 begin_command_inset(os, "nomencl_print", "printnomenclature");
2319 skip_spaces_braces(p);
2322 else if (t.cs() == "url") {
2323 context.check_layout(os);
2324 begin_inset(os, "Flex URL\n");
2325 os << "status collapsed\n";
2326 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2330 else if (LYX_FORMAT >= 408 &&
2331 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2332 context.check_layout(os);
2333 begin_inset(os, "script ");
2334 os << t.cs().substr(4) << '\n';
2335 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2339 else if (is_known(t.cs(), known_quotes)) {
2340 char const * const * where = is_known(t.cs(), known_quotes);
2341 context.check_layout(os);
2342 begin_inset(os, "Quotes ");
2343 os << known_coded_quotes[where - known_quotes];
2345 // LyX adds {} after the quote, so we have to eat
2346 // spaces here if there are any before a possible
2348 eat_whitespace(p, os, context, false);
2352 else if (is_known(t.cs(), known_sizes) &&
2353 context.new_layout_allowed) {
2354 char const * const * where = is_known(t.cs(), known_sizes);
2355 context.check_layout(os);
2356 TeXFont const oldFont = context.font;
2357 context.font.size = known_coded_sizes[where - known_sizes];
2358 output_font_change(os, oldFont, context.font);
2359 eat_whitespace(p, os, context, false);
2362 else if (is_known(t.cs(), known_font_families) &&
2363 context.new_layout_allowed) {
2364 char const * const * where =
2365 is_known(t.cs(), known_font_families);
2366 context.check_layout(os);
2367 TeXFont const oldFont = context.font;
2368 context.font.family =
2369 known_coded_font_families[where - known_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_font_series) &&
2375 context.new_layout_allowed) {
2376 char const * const * where =
2377 is_known(t.cs(), known_font_series);
2378 context.check_layout(os);
2379 TeXFont const oldFont = context.font;
2380 context.font.series =
2381 known_coded_font_series[where - known_font_series];
2382 output_font_change(os, oldFont, context.font);
2383 eat_whitespace(p, os, context, false);
2386 else if (is_known(t.cs(), known_font_shapes) &&
2387 context.new_layout_allowed) {
2388 char const * const * where =
2389 is_known(t.cs(), known_font_shapes);
2390 context.check_layout(os);
2391 TeXFont const oldFont = context.font;
2392 context.font.shape =
2393 known_coded_font_shapes[where - known_font_shapes];
2394 output_font_change(os, oldFont, context.font);
2395 eat_whitespace(p, os, context, false);
2397 else if (is_known(t.cs(), known_old_font_families) &&
2398 context.new_layout_allowed) {
2399 char const * const * where =
2400 is_known(t.cs(), known_old_font_families);
2401 context.check_layout(os);
2402 TeXFont const oldFont = context.font;
2403 context.font.init();
2404 context.font.size = oldFont.size;
2405 context.font.family =
2406 known_coded_font_families[where - known_old_font_families];
2407 output_font_change(os, oldFont, context.font);
2408 eat_whitespace(p, os, context, false);
2411 else if (is_known(t.cs(), known_old_font_series) &&
2412 context.new_layout_allowed) {
2413 char const * const * where =
2414 is_known(t.cs(), known_old_font_series);
2415 context.check_layout(os);
2416 TeXFont const oldFont = context.font;
2417 context.font.init();
2418 context.font.size = oldFont.size;
2419 context.font.series =
2420 known_coded_font_series[where - known_old_font_series];
2421 output_font_change(os, oldFont, context.font);
2422 eat_whitespace(p, os, context, false);
2425 else if (is_known(t.cs(), known_old_font_shapes) &&
2426 context.new_layout_allowed) {
2427 char const * const * where =
2428 is_known(t.cs(), known_old_font_shapes);
2429 context.check_layout(os);
2430 TeXFont const oldFont = context.font;
2431 context.font.init();
2432 context.font.size = oldFont.size;
2433 context.font.shape =
2434 known_coded_font_shapes[where - known_old_font_shapes];
2435 output_font_change(os, oldFont, context.font);
2436 eat_whitespace(p, os, context, false);
2439 else if (t.cs() == "selectlanguage") {
2440 context.check_layout(os);
2441 // save the language for the case that a
2442 // \foreignlanguage is used
2444 // FIXME: \lang needs a LyX name, but we set a LaTeX name
2445 context.font.language = subst(p.verbatim_item(), "\n", " ");
2446 os << "\\lang " << context.font.language << "\n";
2449 else if (t.cs() == "foreignlanguage") {
2450 context.check_layout(os);
2451 // FIXME: \lang needs a LyX name, but we set a LaTeX name
2452 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2453 os << subst(p.verbatim_item(), "\n", " ");
2454 // FIXME: the second argument of selectlanguage
2455 // has to be parsed (like for \textsf, for
2457 // set back to last selectlanguage
2458 os << "\n\\lang " << context.font.language << "\n";
2461 else if (t.cs() == "inputencoding") {
2462 // nothing to write here
2463 string const enc = subst(p.verbatim_item(), "\n", " ");
2467 else if (t.cs() == "ldots") {
2468 context.check_layout(os);
2469 os << "\\SpecialChar \\ldots{}\n";
2470 skip_spaces_braces(p);
2473 else if (t.cs() == "lyxarrow") {
2474 context.check_layout(os);
2475 os << "\\SpecialChar \\menuseparator\n";
2476 skip_spaces_braces(p);
2479 else if (t.cs() == "textcompwordmark") {
2480 context.check_layout(os);
2481 os << "\\SpecialChar \\textcompwordmark{}\n";
2482 skip_spaces_braces(p);
2485 else if (t.cs() == "slash") {
2486 context.check_layout(os);
2487 os << "\\SpecialChar \\slash{}\n";
2488 skip_spaces_braces(p);
2491 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2492 context.check_layout(os);
2493 os << "\\SpecialChar \\nobreakdash-\n";
2497 else if (t.cs() == "textquotedbl") {
2498 context.check_layout(os);
2503 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2504 context.check_layout(os);
2505 os << "\\SpecialChar \\@.\n";
2509 else if (t.cs() == "-") {
2510 context.check_layout(os);
2511 os << "\\SpecialChar \\-\n";
2514 else if (t.cs() == "textasciitilde") {
2515 context.check_layout(os);
2517 skip_spaces_braces(p);
2520 else if (t.cs() == "textasciicircum") {
2521 context.check_layout(os);
2523 skip_spaces_braces(p);
2526 else if (t.cs() == "textbackslash") {
2527 context.check_layout(os);
2528 os << "\n\\backslash\n";
2529 skip_spaces_braces(p);
2532 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2533 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2535 context.check_layout(os);
2539 else if (t.cs() == "char") {
2540 context.check_layout(os);
2541 if (p.next_token().character() == '`') {
2543 if (p.next_token().cs() == "\"") {
2548 handle_ert(os, "\\char`", context);
2551 handle_ert(os, "\\char", context);
2555 else if (t.cs() == "verb") {
2556 context.check_layout(os);
2557 char const delimiter = p.next_token().character();
2558 string const arg = p.getArg(delimiter, delimiter);
2560 oss << "\\verb" << delimiter << arg << delimiter;
2561 handle_ert(os, oss.str(), context);
2564 // Problem: \= creates a tabstop inside the tabbing environment
2565 // and else an accent. In the latter case we really would want
2566 // \={o} instead of \= o.
2567 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2568 handle_ert(os, t.asInput(), context);
2570 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2571 else if (t.cs().size() == 1
2572 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2573 context.check_layout(os);
2574 // try to see whether the string is in unicodesymbols
2576 string command = t.asInput() + "{"
2577 + trim(p.verbatim_item())
2579 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2582 cerr << "When parsing " << command
2583 << ", result is " << to_utf8(s)
2584 << "+" << to_utf8(rem) << endl;
2587 // we did not find a non-ert version
2588 handle_ert(os, command, context);
2591 else if (t.cs() == "\\") {
2592 context.check_layout(os);
2594 handle_ert(os, "\\\\" + p.getOpt(), context);
2595 else if (p.next_token().asInput() == "*") {
2597 // getOpt() eats the following space if there
2598 // is no optional argument, but that is OK
2599 // here since it has no effect in the output.
2600 handle_ert(os, "\\\\*" + p.getOpt(), context);
2603 begin_inset(os, "Newline newline");
2608 else if (t.cs() == "newline" ||
2609 (t.cs() == "linebreak" && !p.hasOpt())) {
2610 context.check_layout(os);
2611 begin_inset(os, "Newline ");
2614 skip_spaces_braces(p);
2617 else if (t.cs() == "input" || t.cs() == "include"
2618 || t.cs() == "verbatiminput") {
2619 string name = t.cs();
2620 if (t.cs() == "verbatiminput"
2621 && p.next_token().asInput() == "*")
2622 name += p.get_token().asInput();
2623 context.check_layout(os);
2624 string filename(normalize_filename(p.getArg('{', '}')));
2625 string const path = getMasterFilePath();
2626 // We want to preserve relative / absolute filenames,
2627 // therefore path is only used for testing
2628 if ((t.cs() == "include" || t.cs() == "input") &&
2629 !makeAbsPath(filename, path).exists()) {
2630 // The file extension is probably missing.
2631 // Now try to find it out.
2632 string const tex_name =
2633 find_file(filename, path,
2634 known_tex_extensions);
2635 if (!tex_name.empty())
2636 filename = tex_name;
2638 bool external = false;
2640 if (makeAbsPath(filename, path).exists()) {
2641 string const abstexname =
2642 makeAbsPath(filename, path).absFileName();
2643 string const abslyxname =
2644 changeExtension(abstexname, ".lyx");
2645 string const absfigname =
2646 changeExtension(abstexname, ".fig");
2647 fix_relative_filename(filename);
2648 string const lyxname =
2649 changeExtension(filename, ".lyx");
2651 external = FileName(absfigname).exists();
2652 if (t.cs() == "input") {
2653 string const ext = getExtension(abstexname);
2655 // Combined PS/LaTeX:
2656 // x.eps, x.pstex_t (old xfig)
2657 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2658 FileName const absepsname(
2659 changeExtension(abstexname, ".eps"));
2660 FileName const abspstexname(
2661 changeExtension(abstexname, ".pstex"));
2662 bool const xfigeps =
2663 (absepsname.exists() ||
2664 abspstexname.exists()) &&
2667 // Combined PDF/LaTeX:
2668 // x.pdf, x.pdftex_t (old xfig)
2669 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2670 FileName const abspdfname(
2671 changeExtension(abstexname, ".pdf"));
2672 bool const xfigpdf =
2673 abspdfname.exists() &&
2674 (ext == "pdftex_t" || ext == "pdf_t");
2678 // Combined PS/PDF/LaTeX:
2679 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2680 string const absbase2(
2681 removeExtension(abstexname) + "_pspdftex");
2682 FileName const abseps2name(
2683 addExtension(absbase2, ".eps"));
2684 FileName const abspdf2name(
2685 addExtension(absbase2, ".pdf"));
2686 bool const xfigboth =
2687 abspdf2name.exists() &&
2688 abseps2name.exists() && ext == "pspdftex";
2690 xfig = xfigpdf || xfigeps || xfigboth;
2691 external = external && xfig;
2694 outname = changeExtension(filename, ".fig");
2696 // Don't try to convert, the result
2697 // would be full of ERT.
2699 } else if (t.cs() != "verbatiminput" &&
2700 tex2lyx(abstexname, FileName(abslyxname),
2707 cerr << "Warning: Could not find included file '"
2708 << filename << "'." << endl;
2712 begin_inset(os, "External\n");
2713 os << "\ttemplate XFig\n"
2714 << "\tfilename " << outname << '\n';
2716 begin_command_inset(os, "include", name);
2717 os << "preview false\n"
2718 "filename \"" << outname << "\"\n";
2723 else if (t.cs() == "bibliographystyle") {
2724 // store new bibliographystyle
2725 bibliographystyle = p.verbatim_item();
2726 // If any other command than \bibliography and
2727 // \nocite{*} follows, we need to output the style
2728 // (because it might be used by that command).
2729 // Otherwise, it will automatically be output by LyX.
2732 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
2733 if (t2.cat() == catBegin)
2735 if (t2.cat() != catEscape)
2737 if (t2.cs() == "nocite") {
2738 if (p.getArg('{', '}') == "*")
2740 } else if (t2.cs() == "bibliography")
2747 "\\bibliographystyle{" + bibliographystyle + '}',
2752 else if (t.cs() == "bibliography") {
2753 context.check_layout(os);
2754 begin_command_inset(os, "bibtex", "bibtex");
2755 if (!btprint.empty()) {
2756 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2757 // clear the string because the next BibTeX inset can be without the
2758 // \nocite{*} option
2761 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2762 // Do we have a bibliographystyle set?
2763 if (!bibliographystyle.empty())
2764 os << "options " << '"' << bibliographystyle << '"' << "\n";
2768 else if (t.cs() == "parbox")
2769 parse_box(p, os, FLAG_ITEM, outer, context, true);
2771 //\makebox() is part of the picture environment and different from \makebox{}
2772 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2773 else if (t.cs() == "makebox") {
2774 string arg = t.asInput();
2775 if (p.next_token().character() == '(')
2776 //the syntax is: \makebox(x,y)[position]{content}
2777 arg += p.getFullParentheseArg();
2779 //the syntax is: \makebox[width][position]{content}
2780 arg += p.getFullOpt();
2781 handle_ert(os, arg + p.getFullOpt(), context);
2784 else if (t.cs() == "smallskip" ||
2785 t.cs() == "medskip" ||
2786 t.cs() == "bigskip" ||
2787 t.cs() == "vfill") {
2788 context.check_layout(os);
2789 begin_inset(os, "VSpace ");
2792 skip_spaces_braces(p);
2795 else if (is_known(t.cs(), known_spaces)) {
2796 char const * const * where = is_known(t.cs(), known_spaces);
2797 context.check_layout(os);
2798 begin_inset(os, "space ");
2799 os << '\\' << known_coded_spaces[where - known_spaces]
2802 // LaTeX swallows whitespace after all spaces except
2803 // "\\,". We have to do that here, too, because LyX
2804 // adds "{}" which would make the spaces significant.
2806 eat_whitespace(p, os, context, false);
2807 // LyX adds "{}" after all spaces except "\\ " and
2808 // "\\,", so we have to remove "{}".
2809 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2810 // remove the braces after "\\,", too.
2815 else if (t.cs() == "newpage" ||
2816 (t.cs() == "pagebreak" && !p.hasOpt()) ||
2817 t.cs() == "clearpage" ||
2818 t.cs() == "cleardoublepage") {
2819 context.check_layout(os);
2820 begin_inset(os, "Newpage ");
2823 skip_spaces_braces(p);
2826 else if (t.cs() == "newcommand" ||
2827 t.cs() == "providecommand" ||
2828 t.cs() == "renewcommand") {
2829 // providecommand could be handled by parse_command(),
2830 // but we need to call add_known_command() here.
2831 string name = t.asInput();
2832 if (p.next_token().asInput() == "*") {
2833 // Starred form. Eat '*'
2837 string const command = p.verbatim_item();
2838 string const opt1 = p.getOpt();
2839 string const opt2 = p.getFullOpt();
2840 add_known_command(command, opt1, !opt2.empty());
2841 string const ert = name + '{' + command + '}' +
2843 '{' + p.verbatim_item() + '}';
2845 if (t.cs() == "providecommand" ||
2846 name[name.length()-1] == '*')
2847 handle_ert(os, ert, context);
2849 context.check_layout(os);
2850 begin_inset(os, "FormulaMacro");
2856 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
2857 // let could be handled by parse_command(),
2858 // but we need to call add_known_command() here.
2859 string ert = t.asInput();
2862 if (p.next_token().cat() == catBegin) {
2863 name = p.verbatim_item();
2864 ert += '{' + name + '}';
2866 name = p.verbatim_item();
2871 if (p.next_token().cat() == catBegin) {
2872 command = p.verbatim_item();
2873 ert += '{' + command + '}';
2875 command = p.verbatim_item();
2878 // If command is known, make name known too, to parse
2879 // its arguments correctly. For this reason we also
2880 // have commands in syntax.default that are hardcoded.
2881 CommandMap::iterator it = known_commands.find(command);
2882 if (it != known_commands.end())
2883 known_commands[t.asInput()] = it->second;
2884 handle_ert(os, ert, context);
2887 else if (t.cs() == "hspace" || t.cs() == "vspace") {
2888 bool starred = false;
2889 if (p.next_token().asInput() == "*") {
2893 string name = t.asInput();
2894 string const length = p.verbatim_item();
2897 bool valid = splitLatexLength(length, valstring, unit);
2898 bool known_hspace = false;
2899 bool known_vspace = false;
2900 bool known_unit = false;
2903 istringstream iss(valstring);
2906 if (t.cs()[0] == 'h') {
2907 if (unit == "\\fill") {
2912 known_hspace = true;
2915 if (unit == "\\smallskipamount") {
2917 known_vspace = true;
2918 } else if (unit == "\\medskipamount") {
2920 known_vspace = true;
2921 } else if (unit == "\\bigskipamount") {
2923 known_vspace = true;
2924 } else if (unit == "\\fill") {
2926 known_vspace = true;
2930 if (!known_hspace && !known_vspace) {
2931 switch (unitFromString(unit)) {
2952 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
2953 // Literal horizontal length or known variable
2954 context.check_layout(os);
2955 begin_inset(os, "space ");
2963 if (known_unit && !known_hspace)
2965 << translate_len(length);
2967 } else if (known_unit || known_vspace) {
2968 // Literal vertical length or known variable
2969 context.check_layout(os);
2970 begin_inset(os, "VSpace ");
2978 // LyX can't handle other length variables in Inset VSpace/space
2983 handle_ert(os, name + '{' + unit + '}', context);
2984 else if (value == -1.0)
2985 handle_ert(os, name + "{-" + unit + '}', context);
2987 handle_ert(os, name + '{' + valstring + unit + '}', context);
2989 handle_ert(os, name + '{' + length + '}', context);
2993 // The single '=' is meant here.
2994 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
2996 context.check_layout(os);
2997 begin_inset(os, "Flex ");
2998 os << to_utf8(newinsetlayout->name()) << '\n'
2999 << "status collapsed\n";
3000 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
3005 // try to see whether the string is in unicodesymbols
3006 // Only use text mode commands, since we are in text mode here,
3007 // and math commands may be invalid (bug 6797)
3009 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3010 rem, Encodings::TEXT_CMD);
3013 cerr << "When parsing " << t.cs()
3014 << ", result is " << to_utf8(s)
3015 << "+" << to_utf8(rem) << endl;
3016 context.check_layout(os);
3018 skip_spaces_braces(p);
3020 //cerr << "#: " << t << " mode: " << mode << endl;
3021 // heuristic: read up to next non-nested space
3023 string s = t.asInput();
3024 string z = p.verbatim_item();
3025 while (p.good() && z != " " && z.size()) {
3026 //cerr << "read: " << z << endl;
3028 z = p.verbatim_item();
3030 cerr << "found ERT: " << s << endl;
3031 handle_ert(os, s + ' ', context);
3034 string name = t.asInput();
3035 if (p.next_token().asInput() == "*") {
3036 // Starred commands like \vspace*{}
3037 p.get_token(); // Eat '*'
3040 if (!parse_command(name, p, os, outer, context))
3041 handle_ert(os, name, context);
3045 if (flags & FLAG_LEAVE) {
3046 flags &= ~FLAG_LEAVE;