2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context, InsetLayout const * layout)
46 bool const forcePlainLayout =
47 layout ? layout->forcePlainLayout() : false;
48 Context newcontext(true, context.textclass);
50 newcontext.layout = &context.textclass.plainLayout();
52 newcontext.font = context.font;
53 parse_text(p, os, flags, outer, newcontext);
54 newcontext.check_end_layout(os);
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61 Context const & context, string const & name)
63 InsetLayout const * layout = 0;
64 DocumentClass::InsetLayouts::const_iterator it =
65 context.textclass.insetLayouts().find(from_ascii(name));
66 if (it != context.textclass.insetLayouts().end())
67 layout = &(it->second);
68 parse_text_in_inset(p, os, flags, outer, context, layout);
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
75 Context newcontext(context);
76 // Don't inherit the paragraph-level extra stuff
77 newcontext.par_extra_stuff.clear();
78 parse_text(p, os, flags, outer, newcontext);
79 // Make sure that we don't create invalid .lyx files
80 context.need_layout = newcontext.need_layout;
81 context.need_end_layout = newcontext.need_end_layout;
86 * Thin wrapper around parse_text_snippet() using a string.
88 * We completely ignore \c context.need_layout and \c context.need_end_layout,
89 * because our return value is not used directly (otherwise the stream version
90 * of parse_text_snippet() could be used). That means that the caller needs
91 * to do layout management manually.
92 * This is intended to parse text that does not create any layout changes.
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
97 Context newcontext(context);
98 newcontext.need_layout = false;
99 newcontext.need_end_layout = false;
100 newcontext.new_layout_allowed = false;
101 // Avoid warning by Context::~Context()
102 newcontext.par_extra_stuff.clear();
104 parse_text_snippet(p, os, flags, outer, newcontext);
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110 "vpageref", "prettyref", "eqref", 0 };
114 * The starred forms are also known except for "citefullauthor",
115 * "citeyear" and "citeyearpar".
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * No starred form other than "cite*" known.
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", 0 };
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
135 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
136 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
137 "guilsinglleft", "frq", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
141 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
142 "gld", "grd", "gls", "ers", "fls",
143 "fls", "frs", "frs", 0};
145 /// LaTeX names for font sizes
146 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
149 /// the same as known_sizes with .lyx names
150 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
153 /// LaTeX 2.09 names for font families
154 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
156 /// LaTeX names for font families
157 char const * const known_font_families[] = { "rmfamily", "sffamily",
160 /// the same as known_old_font_families and known_font_families with .lyx names
161 char const * const known_coded_font_families[] = { "roman", "sans",
164 /// LaTeX 2.09 names for font series
165 char const * const known_old_font_series[] = { "bf", 0};
167 /// LaTeX names for font series
168 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
170 /// the same as known_old_font_series and known_font_series with .lyx names
171 char const * const known_coded_font_series[] = { "bold", "medium", 0};
173 /// LaTeX 2.09 names for font shapes
174 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
176 /// LaTeX names for font shapes
177 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
180 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
181 char const * const known_coded_font_shapes[] = { "italic", "slanted",
182 "smallcaps", "up", 0};
185 * Graphics file extensions known by the dvips driver of the graphics package.
186 * These extensions are used to complete the filename of an included
187 * graphics file if it does not contain an extension.
188 * The order must be the same that latex uses to find a file, because we
189 * will use the first extension that matches.
190 * This is only an approximation for the common cases. If we would want to
191 * do it right in all cases, we would need to know which graphics driver is
192 * used and know the extensions of every driver of the graphics package.
194 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
195 "ps.gz", "eps.Z", "ps.Z", 0};
198 * Graphics file extensions known by the pdftex driver of the graphics package.
199 * \sa known_dvips_graphics_formats
201 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
205 * Known file extensions for TeX files as used by \\include.
207 char const * const known_tex_extensions[] = {"tex", 0};
209 /// spaces known by InsetSpace
210 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
211 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
212 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
214 /// the same as known_spaces with .lyx names
215 char const * const known_coded_spaces[] = { "space{}", "space{}",
216 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
217 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
218 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
220 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
221 /// them in ERT. "LaTeXe" must come before "LaTeX"!
222 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
223 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
224 int const known_phrase_lengths[] = {3, 5, 7, 0};
227 /// splits "x=z, y=b" into a map and an ordered keyword vector
228 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
233 keys.resize(v.size());
234 for (size_t i = 0; i < v.size(); ++i) {
235 size_t const pos = v[i].find('=');
236 string const index = trim(v[i].substr(0, pos));
237 string const value = trim(v[i].substr(pos + 1, string::npos));
245 * Split a LaTeX length into value and unit.
246 * The latter can be a real unit like "pt", or a latex length variable
247 * like "\textwidth". The unit may contain additional stuff like glue
248 * lengths, but we don't care, because such lengths are ERT anyway.
249 * \returns true if \p value and \p unit are valid.
251 bool splitLatexLength(string const & len, string & value, string & unit)
255 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
256 //'4,5' is a valid LaTeX length number. Change it to '4.5'
257 string const length = subst(len, ',', '.');
258 if (i == string::npos)
261 if (len[0] == '\\') {
262 // We had something like \textwidth without a factor
268 value = trim(string(length, 0, i));
272 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
273 if (contains(len, '\\'))
274 unit = trim(string(len, i));
276 unit = ascii_lowercase(trim(string(len, i)));
281 /// A simple function to translate a latex length to something LyX can
282 /// understand. Not perfect, but rather best-effort.
283 bool translate_len(string const & length, string & valstring, string & unit)
285 if (!splitLatexLength(length, valstring, unit))
287 // LyX uses percent values
289 istringstream iss(valstring);
294 string const percentval = oss.str();
296 if (unit.empty() || unit[0] != '\\')
298 string::size_type const i = unit.find(' ');
299 string const endlen = (i == string::npos) ? string() : string(unit, i);
300 if (unit == "\\textwidth") {
301 valstring = percentval;
302 unit = "text%" + endlen;
303 } else if (unit == "\\columnwidth") {
304 valstring = percentval;
305 unit = "col%" + endlen;
306 } else if (unit == "\\paperwidth") {
307 valstring = percentval;
308 unit = "page%" + endlen;
309 } else if (unit == "\\linewidth") {
310 valstring = percentval;
311 unit = "line%" + endlen;
312 } else if (unit == "\\paperheight") {
313 valstring = percentval;
314 unit = "pheight%" + endlen;
315 } else if (unit == "\\textheight") {
316 valstring = percentval;
317 unit = "theight%" + endlen;
325 string translate_len(string const & length)
329 if (translate_len(length, value, unit))
331 // If the input is invalid, return what we have.
339 * Translates a LaTeX length into \p value, \p unit and
340 * \p special parts suitable for a box inset.
341 * The difference from translate_len() is that a box inset knows about
342 * some special "units" that are stored in \p special.
344 void translate_box_len(string const & length, string & value, string & unit, string & special)
346 if (translate_len(length, value, unit)) {
347 if (unit == "\\height" || unit == "\\depth" ||
348 unit == "\\totalheight" || unit == "\\width") {
349 special = unit.substr(1);
350 // The unit is not used, but LyX requires a dummy setting
363 * Find a file with basename \p name in path \p path and an extension
366 string find_file(string const & name, string const & path,
367 char const * const * extensions)
369 for (char const * const * what = extensions; *what; ++what) {
370 string const trial = addExtension(name, *what);
371 if (makeAbsPath(trial, path).exists())
378 void begin_inset(ostream & os, string const & name)
380 os << "\n\\begin_inset " << name;
384 void begin_command_inset(ostream & os, string const & name,
385 string const & latexname)
387 begin_inset(os, "CommandInset ");
388 os << name << "\nLatexCommand " << latexname << '\n';
392 void end_inset(ostream & os)
394 os << "\n\\end_inset\n\n";
398 bool skip_braces(Parser & p)
400 if (p.next_token().cat() != catBegin)
403 if (p.next_token().cat() == catEnd) {
412 void handle_ert(ostream & os, string const & s, Context & context)
414 // We must have a valid layout before outputting the ERT inset.
415 context.check_layout(os);
416 Context newcontext(true, context.textclass);
417 begin_inset(os, "ERT");
418 os << "\nstatus collapsed\n";
419 newcontext.check_layout(os);
420 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
422 os << "\n\\backslash\n";
423 else if (*it == '\n') {
424 newcontext.new_paragraph(os);
425 newcontext.check_layout(os);
429 newcontext.check_end_layout(os);
434 void handle_comment(ostream & os, string const & s, Context & context)
436 // TODO: Handle this better
437 Context newcontext(true, context.textclass);
438 begin_inset(os, "ERT");
439 os << "\nstatus collapsed\n";
440 newcontext.check_layout(os);
441 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
443 os << "\n\\backslash\n";
447 // make sure that our comment is the last thing on the line
448 newcontext.new_paragraph(os);
449 newcontext.check_layout(os);
450 newcontext.check_end_layout(os);
455 Layout const * findLayout(TextClass const & textclass, string const & name)
457 DocumentClass::const_iterator lit = textclass.begin();
458 DocumentClass::const_iterator len = textclass.end();
459 for (; lit != len; ++lit)
460 if (lit->latexname() == name)
466 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
468 DocumentClass::InsetLayouts::const_iterator it = textclass.insetLayouts().begin();
469 DocumentClass::InsetLayouts::const_iterator en = textclass.insetLayouts().end();
470 for (; it != en; ++it)
471 if (it->second.latexname() == name &&
472 ((command && it->second.latextype() == InsetLayout::COMMAND) ||
473 (!command && it->second.latextype() == InsetLayout::ENVIRONMENT)))
474 return &(it->second);
479 void eat_whitespace(Parser &, ostream &, Context &, bool);
483 * Skips whitespace and braces.
484 * This should be called after a command has been parsed that is not put into
485 * ERT, and where LyX adds "{}" if needed.
487 void skip_spaces_braces(Parser & p, bool keepws = false)
489 /* The following four examples produce the same typeset output and
490 should be handled by this function:
498 // Unfortunately we need to skip comments, too.
499 // We can't use eat_whitespace since writing them after the {}
500 // results in different output in some cases.
501 bool const skipped_spaces = p.skip_spaces(true);
502 bool const skipped_braces = skip_braces(p);
503 if (keepws && skipped_spaces && !skipped_braces)
504 // put back the space (it is better handled by check_space)
505 p.unskip_spaces(true);
509 void output_command_layout(ostream & os, Parser & p, bool outer,
510 Context & parent_context,
511 Layout const * newlayout)
513 TeXFont const oldFont = parent_context.font;
514 // save the current font size
515 string const size = oldFont.size;
516 // reset the font size to default, because the font size switches
517 // don't affect section headings and the like
518 parent_context.font.size = Context::normalfont.size;
519 // we only need to write the font change if we have an open layout
520 if (!parent_context.atParagraphStart())
521 output_font_change(os, oldFont, parent_context.font);
522 parent_context.check_end_layout(os);
523 Context context(true, parent_context.textclass, newlayout,
524 parent_context.layout, parent_context.font);
525 if (parent_context.deeper_paragraph) {
526 // We are beginning a nested environment after a
527 // deeper paragraph inside the outer list environment.
528 // Therefore we don't need to output a "begin deeper".
529 context.need_end_deeper = true;
531 context.check_deeper(os);
532 context.check_layout(os);
533 unsigned int optargs = 0;
534 while (optargs < context.layout->optargs) {
535 eat_whitespace(p, os, context, false);
536 if (p.next_token().cat() == catEscape ||
537 p.next_token().character() != '[')
539 p.get_token(); // eat '['
540 begin_inset(os, "OptArg\n");
541 os << "status collapsed\n\n";
542 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
544 eat_whitespace(p, os, context, false);
547 unsigned int reqargs = 0;
548 while (LYX_FORMAT >= 392 && reqargs < context.layout->reqargs) {
549 eat_whitespace(p, os, context, false);
550 if (p.next_token().cat() != catBegin)
552 p.get_token(); // eat '{'
553 begin_inset(os, "OptArg\n");
554 os << "status collapsed\n\n";
555 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
557 eat_whitespace(p, os, context, false);
560 parse_text(p, os, FLAG_ITEM, outer, context);
561 context.check_end_layout(os);
562 if (parent_context.deeper_paragraph) {
563 // We must suppress the "end deeper" because we
564 // suppressed the "begin deeper" above.
565 context.need_end_deeper = false;
567 context.check_end_deeper(os);
568 // We don't need really a new paragraph, but
569 // we must make sure that the next item gets a \begin_layout.
570 parent_context.new_paragraph(os);
571 // Set the font size to the original value. No need to output it here
572 // (Context::begin_layout() will do that if needed)
573 parent_context.font.size = size;
578 * Output a space if necessary.
579 * This function gets called for every whitespace token.
581 * We have three cases here:
582 * 1. A space must be suppressed. Example: The lyxcode case below
583 * 2. A space may be suppressed. Example: Spaces before "\par"
584 * 3. A space must not be suppressed. Example: A space between two words
586 * We currently handle only 1. and 3 and from 2. only the case of
587 * spaces before newlines as a side effect.
589 * 2. could be used to suppress as many spaces as possible. This has two effects:
590 * - Reimporting LyX generated LaTeX files changes almost no whitespace
591 * - Superflous whitespace from non LyX generated LaTeX files is removed.
592 * The drawback is that the logic inside the function becomes
593 * complicated, and that is the reason why it is not implemented.
595 void check_space(Parser & p, ostream & os, Context & context)
597 Token const next = p.next_token();
598 Token const curr = p.curr_token();
599 // A space before a single newline and vice versa must be ignored
600 // LyX emits a newline before \end{lyxcode}.
601 // This newline must be ignored,
602 // otherwise LyX will add an additional protected space.
603 if (next.cat() == catSpace ||
604 next.cat() == catNewline ||
605 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
608 context.check_layout(os);
614 * Parse all arguments of \p command
616 void parse_arguments(string const & command,
617 vector<ArgumentType> const & template_arguments,
618 Parser & p, ostream & os, bool outer, Context & context)
620 string ert = command;
621 size_t no_arguments = template_arguments.size();
622 for (size_t i = 0; i < no_arguments; ++i) {
623 switch (template_arguments[i]) {
625 // This argument contains regular LaTeX
626 handle_ert(os, ert + '{', context);
627 eat_whitespace(p, os, context, false);
628 parse_text(p, os, FLAG_ITEM, outer, context);
632 // This argument consists only of a single item.
633 // The presence of '{' or not must be preserved.
635 if (p.next_token().cat() == catBegin)
636 ert += '{' + p.verbatim_item() + '}';
638 ert += p.verbatim_item();
641 // This argument may contain special characters
642 ert += '{' + p.verbatim_item() + '}';
645 // true because we must not eat whitespace
646 ert += p.getOpt(true);
650 handle_ert(os, ert, context);
655 * Check whether \p command is a known command. If yes,
656 * handle the command with all arguments.
657 * \return true if the command was parsed, false otherwise.
659 bool parse_command(string const & command, Parser & p, ostream & os,
660 bool outer, Context & context)
662 if (known_commands.find(command) != known_commands.end()) {
663 parse_arguments(command, known_commands[command], p, os,
671 /// Parses a minipage or parbox
672 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
673 unsigned inner_flags, bool outer, Context & parent_context,
674 string const & outer_type, string const & special,
675 string const & inner_type)
679 string hor_pos = "c";
680 // We need to set the height to the LaTeX default of 1\\totalheight
681 // for the case when no height argument is given
682 string height_value = "1";
683 string height_unit = "in";
684 string height_special = "totalheight";
686 if (!inner_type.empty() && p.hasOpt()) {
687 position = p.getArg('[', ']');
688 if (position != "t" && position != "c" && position != "b") {
689 cerr << "invalid position " << position << " for "
690 << inner_type << endl;
694 latex_height = p.getArg('[', ']');
695 translate_box_len(latex_height, height_value, height_unit, height_special);
698 inner_pos = p.getArg('[', ']');
699 if (inner_pos != "c" && inner_pos != "t" &&
700 inner_pos != "b" && inner_pos != "s") {
701 cerr << "invalid inner_pos "
702 << inner_pos << " for "
703 << inner_type << endl;
704 inner_pos = position;
712 if (inner_type.empty()) {
714 latex_width = "\\columnwidth";
717 latex_width = p2.getOptContent();
718 string const opt = p2.getOptContent();
721 if (hor_pos != "l" && hor_pos != "c" &&
723 cerr << "invalid hor_pos " << hor_pos
724 << " for " << outer_type << endl;
730 latex_width = p.verbatim_item();
731 translate_len(latex_width, width_value, width_unit);
732 // LyX can't handle length variables
733 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
734 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
735 // Look whether there is some content after the end of the
736 // inner box, but before the end of the outer box.
737 // If yes, we need to output ERT.
739 if (inner_flags & FLAG_END)
740 p.verbatimEnvironment(inner_type);
744 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
745 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
746 // something is between the end of the inner box and
747 // the end of the outer box, so we need to use ERT.
754 if (!outer_type.empty()) {
755 if (outer_flags & FLAG_END)
756 ss << "\\begin{" << outer_type << '}';
758 ss << '\\' << outer_type << '{';
759 if (!special.empty())
763 if (!inner_type.empty()) {
764 if (inner_flags & FLAG_END)
765 ss << "\\begin{" << inner_type << '}';
767 ss << '\\' << inner_type;
768 if (!position.empty())
769 ss << '[' << position << ']';
770 if (!latex_height.empty())
771 ss << '[' << latex_height << ']';
772 if (!inner_pos.empty())
773 ss << '[' << inner_pos << ']';
774 ss << '{' << latex_width << '}';
775 if (!(inner_flags & FLAG_END))
778 handle_ert(os, ss.str(), parent_context);
779 if (!inner_type.empty()) {
780 parse_text(p, os, inner_flags, outer, parent_context);
781 if (inner_flags & FLAG_END)
782 handle_ert(os, "\\end{" + inner_type + '}',
785 handle_ert(os, "}", parent_context);
787 if (!outer_type.empty()) {
788 parse_text(p, os, outer_flags, outer, parent_context);
789 if (outer_flags & FLAG_END)
790 handle_ert(os, "\\end{" + outer_type + '}',
793 handle_ert(os, "}", parent_context);
796 // LyX does not like empty positions, so we have
797 // to set them to the LaTeX default values here.
798 if (position.empty())
800 if (inner_pos.empty())
801 inner_pos = position;
802 parent_context.check_layout(os);
803 begin_inset(os, "Box ");
804 if (outer_type == "framed")
806 else if (outer_type == "framebox")
808 else if (outer_type == "shadowbox")
810 else if (outer_type == "shaded")
812 else if (outer_type == "doublebox")
814 else if (outer_type.empty())
817 os << outer_type << '\n';
818 os << "position \"" << position << "\"\n";
819 os << "hor_pos \"" << hor_pos << "\"\n";
820 os << "has_inner_box " << !inner_type.empty() << "\n";
821 os << "inner_pos \"" << inner_pos << "\"\n";
822 os << "use_parbox " << (inner_type == "parbox") << '\n';
823 os << "width \"" << width_value << width_unit << "\"\n";
824 os << "special \"none\"\n";
825 os << "height \"" << height_value << height_unit << "\"\n";
826 os << "height_special \"" << height_special << "\"\n";
827 os << "status open\n\n";
828 Context context(true, parent_context.textclass);
829 context.font = parent_context.font;
831 // If we have no inner box the contens will be read with the outer box
832 if (!inner_type.empty())
833 parse_text(p, os, inner_flags, outer, context);
835 // Ensure that the end of the outer box is parsed correctly:
836 // The opening brace has been eaten by parse_outer_box()
837 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
838 outer_flags &= ~FLAG_ITEM;
839 outer_flags |= FLAG_BRACE_LAST;
842 // Find end of outer box, output contents if inner_type is
843 // empty and output possible comments
844 if (!outer_type.empty()) {
845 // This does not output anything but comments if
846 // inner_type is not empty (see use_ert)
847 parse_text(p, os, outer_flags, outer, context);
850 context.check_end_layout(os);
852 #ifdef PRESERVE_LAYOUT
853 // LyX puts a % after the end of the minipage
854 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
856 //handle_comment(os, "%dummy", parent_context);
859 parent_context.new_paragraph(os);
861 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
862 //handle_comment(os, "%dummy", parent_context);
865 // We add a protected space if something real follows
866 if (p.good() && p.next_token().cat() != catComment) {
867 begin_inset(os, "space ~\n");
876 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
877 Context & parent_context, string const & outer_type,
878 string const & special)
880 eat_whitespace(p, os, parent_context, false);
881 if (flags & FLAG_ITEM) {
883 if (p.next_token().cat() == catBegin)
886 cerr << "Warning: Ignoring missing '{' after \\"
887 << outer_type << '.' << endl;
888 eat_whitespace(p, os, parent_context, false);
891 unsigned int inner_flags = 0;
892 if (outer_type == "shaded") {
893 // These boxes never have an inner box
895 } else if (p.next_token().asInput() == "\\parbox") {
896 inner = p.get_token().cs();
897 inner_flags = FLAG_ITEM;
898 } else if (p.next_token().asInput() == "\\begin") {
899 // Is this a minipage?
902 inner = p.getArg('{', '}');
904 if (inner == "minipage") {
907 eat_whitespace(p, os, parent_context, false);
908 inner_flags = FLAG_END;
912 if (inner_flags == FLAG_END) {
913 active_environments.push_back(inner);
914 parse_box(p, os, flags, FLAG_END, outer, parent_context,
915 outer_type, special, inner);
916 active_environments.pop_back();
918 parse_box(p, os, flags, inner_flags, outer, parent_context,
919 outer_type, special, inner);
924 /// parse an unknown environment
925 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
926 unsigned flags, bool outer,
927 Context & parent_context)
929 if (name == "tabbing")
930 // We need to remember that we have to handle '\=' specially
931 flags |= FLAG_TABBING;
933 // We need to translate font changes and paragraphs inside the
934 // environment to ERT if we have a non standard font.
935 // Otherwise things like
936 // \large\begin{foo}\huge bar\end{foo}
938 bool const specialfont =
939 (parent_context.font != parent_context.normalfont);
940 bool const new_layout_allowed = parent_context.new_layout_allowed;
942 parent_context.new_layout_allowed = false;
943 handle_ert(os, "\\begin{" + name + "}", parent_context);
944 parse_text_snippet(p, os, flags, outer, parent_context);
945 handle_ert(os, "\\end{" + name + "}", parent_context);
947 parent_context.new_layout_allowed = new_layout_allowed;
951 void parse_environment(Parser & p, ostream & os, bool outer,
952 string & last_env, Context & parent_context)
954 Layout const * newlayout;
955 string const name = p.getArg('{', '}');
956 const bool is_starred = suffixIs(name, '*');
957 string const unstarred_name = rtrim(name, "*");
958 active_environments.push_back(name);
960 if (is_math_env(name)) {
961 parent_context.check_layout(os);
962 begin_inset(os, "Formula ");
963 os << "\\begin{" << name << "}";
964 parse_math(p, os, FLAG_END, MATH_MODE);
965 os << "\\end{" << name << "}";
969 else if (name == "tabular" || name == "longtable") {
970 eat_whitespace(p, os, parent_context, false);
971 parent_context.check_layout(os);
972 begin_inset(os, "Tabular ");
973 handle_tabular(p, os, name == "longtable", parent_context);
978 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
979 eat_whitespace(p, os, parent_context, false);
980 parent_context.check_layout(os);
981 begin_inset(os, "Float " + unstarred_name + "\n");
983 os << "placement " << p.getArg('[', ']') << '\n';
984 os << "wide " << convert<string>(is_starred)
985 << "\nsideways false"
986 << "\nstatus open\n\n";
987 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
989 // We don't need really a new paragraph, but
990 // we must make sure that the next item gets a \begin_layout.
991 parent_context.new_paragraph(os);
995 else if (name == "minipage") {
996 eat_whitespace(p, os, parent_context, false);
997 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1001 else if (name == "comment") {
1002 eat_whitespace(p, os, parent_context, false);
1003 parent_context.check_layout(os);
1004 begin_inset(os, "Note Comment\n");
1005 os << "status open\n";
1006 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1009 skip_braces(p); // eat {} that might by set by LyX behind comments
1012 else if (name == "lyxgreyedout") {
1013 eat_whitespace(p, os, parent_context, false);
1014 parent_context.check_layout(os);
1015 begin_inset(os, "Note Greyedout\n");
1016 os << "status open\n";
1017 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1022 else if (name == "framed" || name == "shaded") {
1023 eat_whitespace(p, os, parent_context, false);
1024 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1028 else if (!parent_context.new_layout_allowed)
1029 parse_unknown_environment(p, name, os, FLAG_END, outer,
1032 // Alignment and spacing settings
1033 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1034 // therefore are totally broken!
1035 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1036 // they are commands not environments. They are furthermore switches that
1037 // can be ended by another switches, but also by commands like \footnote or
1038 // \parbox. So the only safe way is to leave them untouched.
1039 else if (name == "center" || name == "centering" ||
1040 name == "flushleft" || name == "flushright" ||
1041 name == "singlespace" || name == "onehalfspace" ||
1042 name == "doublespace" || name == "spacing") {
1043 eat_whitespace(p, os, parent_context, false);
1044 // We must begin a new paragraph if not already done
1045 if (! parent_context.atParagraphStart()) {
1046 parent_context.check_end_layout(os);
1047 parent_context.new_paragraph(os);
1049 if (name == "flushleft")
1050 parent_context.add_extra_stuff("\\align left\n");
1051 else if (name == "flushright")
1052 parent_context.add_extra_stuff("\\align right\n");
1053 else if (name == "center" || name == "centering")
1054 parent_context.add_extra_stuff("\\align center\n");
1055 else if (name == "singlespace")
1056 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1057 else if (name == "onehalfspace")
1058 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1059 else if (name == "doublespace")
1060 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1061 else if (name == "spacing")
1062 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1063 parse_text(p, os, FLAG_END, outer, parent_context);
1064 // Just in case the environment is empty
1065 parent_context.extra_stuff.erase();
1066 // We must begin a new paragraph to reset the alignment
1067 parent_context.new_paragraph(os);
1071 // The single '=' is meant here.
1072 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
1073 newlayout->isEnvironment()) {
1074 eat_whitespace(p, os, parent_context, false);
1075 Context context(true, parent_context.textclass, newlayout,
1076 parent_context.layout, parent_context.font);
1077 if (parent_context.deeper_paragraph) {
1078 // We are beginning a nested environment after a
1079 // deeper paragraph inside the outer list environment.
1080 // Therefore we don't need to output a "begin deeper".
1081 context.need_end_deeper = true;
1083 parent_context.check_end_layout(os);
1084 if (last_env == name) {
1085 // we need to output a separator since LyX would export
1086 // the two environments as one otherwise (bug 5716)
1087 docstring const sep = from_ascii("--Separator--");
1088 TeX2LyXDocClass const & textclass(parent_context.textclass);
1089 if (textclass.hasLayout(sep)) {
1090 Context newcontext(parent_context);
1091 newcontext.layout = &(textclass[sep]);
1092 newcontext.check_layout(os);
1093 newcontext.check_end_layout(os);
1095 parent_context.check_layout(os);
1096 begin_inset(os, "Note Note\n");
1097 os << "status closed\n";
1098 Context newcontext(true, textclass,
1099 &(textclass.defaultLayout()));
1100 newcontext.check_layout(os);
1101 newcontext.check_end_layout(os);
1103 parent_context.check_end_layout(os);
1106 switch (context.layout->latextype) {
1107 case LATEX_LIST_ENVIRONMENT:
1108 context.add_par_extra_stuff("\\labelwidthstring "
1109 + p.verbatim_item() + '\n');
1112 case LATEX_BIB_ENVIRONMENT:
1113 p.verbatim_item(); // swallow next arg
1119 context.check_deeper(os);
1120 parse_text(p, os, FLAG_END, outer, context);
1121 context.check_end_layout(os);
1122 if (parent_context.deeper_paragraph) {
1123 // We must suppress the "end deeper" because we
1124 // suppressed the "begin deeper" above.
1125 context.need_end_deeper = false;
1127 context.check_end_deeper(os);
1128 parent_context.new_paragraph(os);
1132 else if (name == "appendix") {
1133 // This is no good latex style, but it works and is used in some documents...
1134 eat_whitespace(p, os, parent_context, false);
1135 parent_context.check_end_layout(os);
1136 Context context(true, parent_context.textclass, parent_context.layout,
1137 parent_context.layout, parent_context.font);
1138 context.check_layout(os);
1139 os << "\\start_of_appendix\n";
1140 parse_text(p, os, FLAG_END, outer, context);
1141 context.check_end_layout(os);
1145 else if (known_environments.find(name) != known_environments.end()) {
1146 vector<ArgumentType> arguments = known_environments[name];
1147 // The last "argument" denotes wether we may translate the
1148 // environment contents to LyX
1149 // The default required if no argument is given makes us
1150 // compatible with the reLyXre environment.
1151 ArgumentType contents = arguments.empty() ?
1154 if (!arguments.empty())
1155 arguments.pop_back();
1156 // See comment in parse_unknown_environment()
1157 bool const specialfont =
1158 (parent_context.font != parent_context.normalfont);
1159 bool const new_layout_allowed =
1160 parent_context.new_layout_allowed;
1162 parent_context.new_layout_allowed = false;
1163 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1164 outer, parent_context);
1165 if (contents == verbatim)
1166 handle_ert(os, p.verbatimEnvironment(name),
1169 parse_text_snippet(p, os, FLAG_END, outer,
1171 handle_ert(os, "\\end{" + name + "}", parent_context);
1173 parent_context.new_layout_allowed = new_layout_allowed;
1177 parse_unknown_environment(p, name, os, FLAG_END, outer,
1181 active_environments.pop_back();
1185 /// parses a comment and outputs it to \p os.
1186 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1188 LASSERT(t.cat() == catComment, return);
1189 if (!t.cs().empty()) {
1190 context.check_layout(os);
1191 handle_comment(os, '%' + t.cs(), context);
1192 if (p.next_token().cat() == catNewline) {
1193 // A newline after a comment line starts a new
1195 if (context.new_layout_allowed) {
1196 if(!context.atParagraphStart())
1197 // Only start a new paragraph if not already
1198 // done (we might get called recursively)
1199 context.new_paragraph(os);
1201 handle_ert(os, "\n", context);
1202 eat_whitespace(p, os, context, true);
1205 // "%\n" combination
1212 * Reads spaces and comments until the first non-space, non-comment token.
1213 * New paragraphs (double newlines or \\par) are handled like simple spaces
1214 * if \p eatParagraph is true.
1215 * Spaces are skipped, but comments are written to \p os.
1217 void eat_whitespace(Parser & p, ostream & os, Context & context,
1221 Token const & t = p.get_token();
1222 if (t.cat() == catComment)
1223 parse_comment(p, os, t, context);
1224 else if ((! eatParagraph && p.isParagraph()) ||
1225 (t.cat() != catSpace && t.cat() != catNewline)) {
1234 * Set a font attribute, parse text and reset the font attribute.
1235 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1236 * \param currentvalue Current value of the attribute. Is set to the new
1237 * value during parsing.
1238 * \param newvalue New value of the attribute
1240 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1241 Context & context, string const & attribute,
1242 string & currentvalue, string const & newvalue)
1244 context.check_layout(os);
1245 string const oldvalue = currentvalue;
1246 currentvalue = newvalue;
1247 os << '\n' << attribute << ' ' << newvalue << "\n";
1248 parse_text_snippet(p, os, flags, outer, context);
1249 context.check_layout(os);
1250 os << '\n' << attribute << ' ' << oldvalue << "\n";
1251 currentvalue = oldvalue;
1255 /// get the arguments of a natbib or jurabib citation command
1256 void get_cite_arguments(Parser & p, bool natbibOrder,
1257 string & before, string & after)
1259 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1261 // text before the citation
1263 // text after the citation
1264 after = p.getFullOpt();
1266 if (!after.empty()) {
1267 before = p.getFullOpt();
1268 if (natbibOrder && !before.empty())
1269 swap(before, after);
1274 /// Convert filenames with TeX macros and/or quotes to something LyX
1276 string const normalize_filename(string const & name)
1278 Parser p(trim(name, "\""));
1281 Token const & t = p.get_token();
1282 if (t.cat() != catEscape)
1284 else if (t.cs() == "lyxdot") {
1285 // This is used by LyX for simple dots in relative
1289 } else if (t.cs() == "space") {
1299 /// Convert \p name from TeX convention (relative to master file) to LyX
1300 /// convention (relative to .lyx file) if it is relative
1301 void fix_relative_filename(string & name)
1303 if (FileName::isAbsolute(name))
1306 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1307 from_utf8(getParentFilePath())));
1311 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1312 void parse_noweb(Parser & p, ostream & os, Context & context)
1314 // assemble the rest of the keyword
1318 Token const & t = p.get_token();
1319 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1322 scrap = (p.good() && p.next_token().asInput() == "=");
1324 name += p.get_token().asInput();
1327 name += t.asInput();
1330 if (!scrap || !context.new_layout_allowed ||
1331 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1332 cerr << "Warning: Could not interpret '" << name
1333 << "'. Ignoring it." << endl;
1337 // We use new_paragraph instead of check_end_layout because the stuff
1338 // following the noweb chunk needs to start with a \begin_layout.
1339 // This may create a new paragraph even if there was none in the
1340 // noweb file, but the alternative is an invalid LyX file. Since
1341 // noweb code chunks are implemented with a layout style in LyX they
1342 // always must be in an own paragraph.
1343 context.new_paragraph(os);
1344 Context newcontext(true, context.textclass,
1345 &context.textclass[from_ascii("Scrap")]);
1346 newcontext.check_layout(os);
1349 Token const & t = p.get_token();
1350 // We abuse the parser a bit, because this is no TeX syntax
1352 if (t.cat() == catEscape)
1353 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1356 begin_inset(oss, "Newline newline");
1358 os << subst(t.asInput(), "\n", oss.str());
1360 // The scrap chunk is ended by an @ at the beginning of a line.
1361 // After the @ the line may contain a comment and/or
1362 // whitespace, but nothing else.
1363 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1364 (p.next_token().cat() == catSpace ||
1365 p.next_token().cat() == catNewline ||
1366 p.next_token().cat() == catComment)) {
1367 while (p.good() && p.next_token().cat() == catSpace)
1368 os << p.get_token().asInput();
1369 if (p.next_token().cat() == catComment)
1370 // The comment includes a final '\n'
1371 os << p.get_token().asInput();
1373 if (p.next_token().cat() == catNewline)
1380 newcontext.check_end_layout(os);
1384 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1385 bool is_macro(Parser & p)
1387 Token first = p.curr_token();
1388 if (first.cat() != catEscape || !p.good())
1390 if (first.cs() == "def")
1392 if (first.cs() != "global" && first.cs() != "long")
1394 Token second = p.get_token();
1396 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1397 second.cat() == catNewline || second.cat() == catComment)) {
1398 second = p.get_token();
1401 bool secondvalid = second.cat() == catEscape;
1403 bool thirdvalid = false;
1404 if (p.good() && first.cs() == "global" && secondvalid &&
1405 second.cs() == "long") {
1406 third = p.get_token();
1408 while (p.good() && !p.isParagraph() &&
1409 (third.cat() == catSpace ||
1410 third.cat() == catNewline ||
1411 third.cat() == catComment)) {
1412 third = p.get_token();
1415 thirdvalid = third.cat() == catEscape;
1417 for (int i = 0; i < pos; ++i)
1422 return (first.cs() == "global" || first.cs() == "long") &&
1423 second.cs() == "def";
1424 return first.cs() == "global" && second.cs() == "long" &&
1425 third.cs() == "def";
1429 /// Parse a macro definition (assumes that is_macro() returned true)
1430 void parse_macro(Parser & p, ostream & os, Context & context)
1432 context.check_layout(os);
1433 Token first = p.curr_token();
1436 string command = first.asInput();
1437 if (first.cs() != "def") {
1439 eat_whitespace(p, os, context, false);
1440 second = p.curr_token();
1441 command += second.asInput();
1442 if (second.cs() != "def") {
1444 eat_whitespace(p, os, context, false);
1445 third = p.curr_token();
1446 command += third.asInput();
1449 eat_whitespace(p, os, context, false);
1450 string const name = p.get_token().cs();
1451 eat_whitespace(p, os, context, false);
1457 while (p.next_token().cat() != catBegin) {
1458 if (p.next_token().cat() == catParameter) {
1463 // followed by number?
1464 if (p.next_token().cat() == catOther) {
1465 char c = p.getChar();
1467 // number = current arity + 1?
1468 if (c == arity + '0' + 1)
1473 paramtext += p.get_token().cs();
1475 paramtext += p.get_token().cs();
1480 // only output simple (i.e. compatible) macro as FormulaMacros
1481 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1483 context.check_layout(os);
1484 begin_inset(os, "FormulaMacro");
1485 os << "\n\\def" << ert;
1488 handle_ert(os, command + ert, context);
1491 } // anonymous namespace
1494 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1497 Layout const * newlayout = 0;
1498 InsetLayout const * newinsetlayout = 0;
1499 // Store the latest bibliographystyle and nocite{*} option
1500 // (needed for bibtex inset)
1502 string bibliographystyle;
1503 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1504 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1507 Token const & t = p.get_token();
1510 debugToken(cerr, t, flags);
1513 if (flags & FLAG_ITEM) {
1514 if (t.cat() == catSpace)
1517 flags &= ~FLAG_ITEM;
1518 if (t.cat() == catBegin) {
1519 // skip the brace and collect everything to the next matching
1521 flags |= FLAG_BRACE_LAST;
1525 // handle only this single token, leave the loop if done
1526 flags |= FLAG_LEAVE;
1529 if (t.cat() != catEscape && t.character() == ']' &&
1530 (flags & FLAG_BRACK_LAST))
1532 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1535 // If there is anything between \end{env} and \begin{env} we
1536 // don't need to output a separator.
1537 if (t.cat() != catSpace && t.cat() != catNewline &&
1538 t.asInput() != "\\begin")
1544 if (t.cat() == catMath) {
1545 // we are inside some text mode thingy, so opening new math is allowed
1546 context.check_layout(os);
1547 begin_inset(os, "Formula ");
1548 Token const & n = p.get_token();
1549 if (n.cat() == catMath && outer) {
1550 // TeX's $$...$$ syntax for displayed math
1552 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1554 p.get_token(); // skip the second '$' token
1556 // simple $...$ stuff
1559 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1565 else if (t.cat() == catSuper || t.cat() == catSub)
1566 cerr << "catcode " << t << " illegal in text mode\n";
1568 // Basic support for english quotes. This should be
1569 // extended to other quotes, but is not so easy (a
1570 // left english quote is the same as a right german
1572 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1573 context.check_layout(os);
1574 begin_inset(os, "Quotes ");
1580 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1581 context.check_layout(os);
1582 begin_inset(os, "Quotes ");
1589 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1590 context.check_layout(os);
1591 begin_inset(os, "Quotes ");
1598 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1599 context.check_layout(os);
1600 begin_inset(os, "Quotes ");
1607 else if (t.asInput() == "<"
1608 && p.next_token().asInput() == "<" && noweb_mode) {
1610 parse_noweb(p, os, context);
1613 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1614 check_space(p, os, context);
1616 else if (t.character() == '[' && noweb_mode &&
1617 p.next_token().character() == '[') {
1618 // These can contain underscores
1620 string const s = p.getFullOpt() + ']';
1621 if (p.next_token().character() == ']')
1624 cerr << "Warning: Inserting missing ']' in '"
1625 << s << "'." << endl;
1626 handle_ert(os, s, context);
1629 else if (t.cat() == catLetter) {
1630 context.check_layout(os);
1631 // Workaround for bug 4752.
1632 // FIXME: This whole code block needs to be removed
1633 // when the bug is fixed and tex2lyx produces
1634 // the updated file format.
1635 // The replacement algorithm in LyX is so stupid that
1636 // it even translates a phrase if it is part of a word.
1637 bool handled = false;
1638 for (int const * l = known_phrase_lengths; *l; ++l) {
1639 string phrase = t.cs();
1640 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1641 phrase += p.get_token().cs();
1642 if (is_known(phrase, known_coded_phrases)) {
1643 handle_ert(os, phrase, context);
1647 for (size_t i = 1; i < phrase.length(); ++i)
1655 else if (t.cat() == catOther ||
1656 t.cat() == catAlign ||
1657 t.cat() == catParameter) {
1658 // This translates "&" to "\\&" which may be wrong...
1659 context.check_layout(os);
1663 else if (p.isParagraph()) {
1664 if (context.new_layout_allowed)
1665 context.new_paragraph(os);
1667 handle_ert(os, "\\par ", context);
1668 eat_whitespace(p, os, context, true);
1671 else if (t.cat() == catActive) {
1672 context.check_layout(os);
1673 if (t.character() == '~') {
1674 if (context.layout->free_spacing)
1677 begin_inset(os, "space ~\n");
1684 else if (t.cat() == catBegin &&
1685 p.next_token().cat() == catEnd) {
1687 Token const prev = p.prev_token();
1689 if (p.next_token().character() == '`' ||
1690 (prev.character() == '-' &&
1691 p.next_token().character() == '-'))
1692 ; // ignore it in {}`` or -{}-
1694 handle_ert(os, "{}", context);
1698 else if (t.cat() == catBegin) {
1699 context.check_layout(os);
1700 // special handling of font attribute changes
1701 Token const prev = p.prev_token();
1702 Token const next = p.next_token();
1703 TeXFont const oldFont = context.font;
1704 if (next.character() == '[' ||
1705 next.character() == ']' ||
1706 next.character() == '*') {
1708 if (p.next_token().cat() == catEnd) {
1713 handle_ert(os, "{", context);
1714 parse_text_snippet(p, os,
1717 handle_ert(os, "}", context);
1719 } else if (! context.new_layout_allowed) {
1720 handle_ert(os, "{", context);
1721 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1723 handle_ert(os, "}", context);
1724 } else if (is_known(next.cs(), known_sizes)) {
1725 // next will change the size, so we must
1727 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1729 if (!context.atParagraphStart())
1731 << context.font.size << "\n";
1732 } else if (is_known(next.cs(), known_font_families)) {
1733 // next will change the font family, so we
1734 // must reset it here
1735 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1737 if (!context.atParagraphStart())
1739 << context.font.family << "\n";
1740 } else if (is_known(next.cs(), known_font_series)) {
1741 // next will change the font series, so we
1742 // must reset it here
1743 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1745 if (!context.atParagraphStart())
1747 << context.font.series << "\n";
1748 } else if (is_known(next.cs(), known_font_shapes)) {
1749 // next will change the font shape, so we
1750 // must reset it here
1751 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1753 if (!context.atParagraphStart())
1755 << context.font.shape << "\n";
1756 } else if (is_known(next.cs(), known_old_font_families) ||
1757 is_known(next.cs(), known_old_font_series) ||
1758 is_known(next.cs(), known_old_font_shapes)) {
1759 // next will change the font family, series
1760 // and shape, so we must reset it here
1761 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1763 if (!context.atParagraphStart())
1765 << context.font.family
1767 << context.font.series
1769 << context.font.shape << "\n";
1771 handle_ert(os, "{", context);
1772 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1774 handle_ert(os, "}", context);
1778 else if (t.cat() == catEnd) {
1779 if (flags & FLAG_BRACE_LAST) {
1782 cerr << "stray '}' in text\n";
1783 handle_ert(os, "}", context);
1786 else if (t.cat() == catComment)
1787 parse_comment(p, os, t, context);
1790 // control sequences
1793 else if (t.cs() == "(") {
1794 context.check_layout(os);
1795 begin_inset(os, "Formula");
1797 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1802 else if (t.cs() == "[") {
1803 context.check_layout(os);
1804 begin_inset(os, "Formula");
1806 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1811 else if (t.cs() == "begin")
1812 parse_environment(p, os, outer, last_env, context);
1814 else if (t.cs() == "end") {
1815 if (flags & FLAG_END) {
1816 // eat environment name
1817 string const name = p.getArg('{', '}');
1818 if (name != active_environment())
1819 cerr << "\\end{" + name + "} does not match \\begin{"
1820 + active_environment() + "}\n";
1823 p.error("found 'end' unexpectedly");
1826 else if (t.cs() == "item") {
1829 bool optarg = false;
1830 if (p.next_token().cat() != catEscape &&
1831 p.next_token().character() == '[') {
1832 p.get_token(); // eat '['
1833 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1838 context.check_layout(os);
1839 if (context.has_item) {
1840 // An item in an unknown list-like environment
1841 // FIXME: Do this in check_layout()!
1842 context.has_item = false;
1844 handle_ert(os, "\\item", context);
1846 handle_ert(os, "\\item ", context);
1849 if (context.layout->labeltype != LABEL_MANUAL) {
1850 // LyX does not support \item[\mybullet]
1851 // in itemize environments
1852 handle_ert(os, "[", context);
1854 handle_ert(os, "]", context);
1855 } else if (!s.empty()) {
1856 // The space is needed to separate the
1857 // item from the rest of the sentence.
1859 eat_whitespace(p, os, context, false);
1864 else if (t.cs() == "bibitem") {
1866 context.check_layout(os);
1867 begin_command_inset(os, "bibitem", "bibitem");
1868 os << "label \"" << p.getOptContent() << "\"\n";
1869 os << "key \"" << p.verbatim_item() << "\"\n";
1873 else if (is_macro(p))
1874 parse_macro(p, os, context);
1876 else if (t.cs() == "noindent") {
1878 context.add_par_extra_stuff("\\noindent\n");
1881 else if (t.cs() == "appendix") {
1882 context.add_par_extra_stuff("\\start_of_appendix\n");
1883 // We need to start a new paragraph. Otherwise the
1884 // appendix in 'bla\appendix\chapter{' would start
1886 context.new_paragraph(os);
1887 // We need to make sure that the paragraph is
1888 // generated even if it is empty. Otherwise the
1889 // appendix in '\par\appendix\par\chapter{' would
1891 context.check_layout(os);
1892 // FIXME: This is a hack to prevent paragraph
1893 // deletion if it is empty. Handle this better!
1895 "%dummy comment inserted by tex2lyx to "
1896 "ensure that this paragraph is not empty",
1898 // Both measures above may generate an additional
1899 // empty paragraph, but that does not hurt, because
1900 // whitespace does not matter here.
1901 eat_whitespace(p, os, context, true);
1904 // Starred section headings
1905 // Must attempt to parse "Section*" before "Section".
1906 else if ((p.next_token().asInput() == "*") &&
1907 context.new_layout_allowed &&
1908 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1909 newlayout->isCommand()) {
1912 output_command_layout(os, p, outer, context, newlayout);
1916 // Section headings and the like
1917 else if (context.new_layout_allowed &&
1918 (newlayout = findLayout(context.textclass, t.cs())) &&
1919 newlayout->isCommand()) {
1921 output_command_layout(os, p, outer, context, newlayout);
1925 else if (t.cs() == "caption") {
1927 context.check_layout(os);
1929 begin_inset(os, "Caption\n\n");
1930 Context newcontext(true, context.textclass);
1931 newcontext.font = context.font;
1932 newcontext.check_layout(os);
1933 if (p.next_token().cat() != catEscape &&
1934 p.next_token().character() == '[') {
1935 p.get_token(); // eat '['
1936 begin_inset(os, "OptArg\n");
1937 os << "status collapsed\n";
1938 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1940 eat_whitespace(p, os, context, false);
1942 parse_text(p, os, FLAG_ITEM, outer, context);
1943 context.check_end_layout(os);
1944 // We don't need really a new paragraph, but
1945 // we must make sure that the next item gets a \begin_layout.
1946 context.new_paragraph(os);
1949 newcontext.check_end_layout(os);
1952 else if (t.cs() == "includegraphics") {
1953 bool const clip = p.next_token().asInput() == "*";
1956 string const arg = p.getArg('[', ']');
1957 map<string, string> opts;
1958 vector<string> keys;
1959 split_map(arg, opts, keys);
1961 opts["clip"] = string();
1962 string name = normalize_filename(p.verbatim_item());
1964 string const path = getMasterFilePath();
1965 // We want to preserve relative / absolute filenames,
1966 // therefore path is only used for testing
1967 if (!makeAbsPath(name, path).exists()) {
1968 // The file extension is probably missing.
1969 // Now try to find it out.
1970 string const dvips_name =
1971 find_file(name, path,
1972 known_dvips_graphics_formats);
1973 string const pdftex_name =
1974 find_file(name, path,
1975 known_pdftex_graphics_formats);
1976 if (!dvips_name.empty()) {
1977 if (!pdftex_name.empty()) {
1978 cerr << "This file contains the "
1980 "\"\\includegraphics{"
1982 "However, files\n\""
1983 << dvips_name << "\" and\n\""
1984 << pdftex_name << "\"\n"
1985 "both exist, so I had to make a "
1986 "choice and took the first one.\n"
1987 "Please move the unwanted one "
1988 "someplace else and try again\n"
1989 "if my choice was wrong."
1993 } else if (!pdftex_name.empty()) {
1999 if (makeAbsPath(name, path).exists())
2000 fix_relative_filename(name);
2002 cerr << "Warning: Could not find graphics file '"
2003 << name << "'." << endl;
2005 context.check_layout(os);
2006 begin_inset(os, "Graphics ");
2007 os << "\n\tfilename " << name << '\n';
2008 if (opts.find("width") != opts.end())
2010 << translate_len(opts["width"]) << '\n';
2011 if (opts.find("height") != opts.end())
2013 << translate_len(opts["height"]) << '\n';
2014 if (opts.find("scale") != opts.end()) {
2015 istringstream iss(opts["scale"]);
2019 os << "\tscale " << val << '\n';
2021 if (opts.find("angle") != opts.end()) {
2022 os << "\trotateAngle "
2023 << opts["angle"] << '\n';
2024 vector<string>::const_iterator a =
2025 find(keys.begin(), keys.end(), "angle");
2026 vector<string>::const_iterator s =
2027 find(keys.begin(), keys.end(), "width");
2028 if (s == keys.end())
2029 s = find(keys.begin(), keys.end(), "height");
2030 if (s == keys.end())
2031 s = find(keys.begin(), keys.end(), "scale");
2032 if (s != keys.end() && distance(s, a) > 0)
2033 os << "\tscaleBeforeRotation\n";
2035 if (opts.find("origin") != opts.end()) {
2037 string const opt = opts["origin"];
2038 if (opt.find('l') != string::npos) ss << "left";
2039 if (opt.find('r') != string::npos) ss << "right";
2040 if (opt.find('c') != string::npos) ss << "center";
2041 if (opt.find('t') != string::npos) ss << "Top";
2042 if (opt.find('b') != string::npos) ss << "Bottom";
2043 if (opt.find('B') != string::npos) ss << "Baseline";
2044 if (!ss.str().empty())
2045 os << "\trotateOrigin " << ss.str() << '\n';
2047 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2049 if (opts.find("keepaspectratio") != opts.end())
2050 os << "\tkeepAspectRatio\n";
2051 if (opts.find("clip") != opts.end())
2053 if (opts.find("draft") != opts.end())
2055 if (opts.find("bb") != opts.end())
2056 os << "\tBoundingBox "
2057 << opts["bb"] << '\n';
2058 int numberOfbbOptions = 0;
2059 if (opts.find("bbllx") != opts.end())
2060 numberOfbbOptions++;
2061 if (opts.find("bblly") != opts.end())
2062 numberOfbbOptions++;
2063 if (opts.find("bburx") != opts.end())
2064 numberOfbbOptions++;
2065 if (opts.find("bbury") != opts.end())
2066 numberOfbbOptions++;
2067 if (numberOfbbOptions == 4)
2068 os << "\tBoundingBox "
2069 << opts["bbllx"] << " " << opts["bblly"] << " "
2070 << opts["bburx"] << " " << opts["bbury"] << '\n';
2071 else if (numberOfbbOptions > 0)
2072 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2073 numberOfbbOptions = 0;
2074 if (opts.find("natwidth") != opts.end())
2075 numberOfbbOptions++;
2076 if (opts.find("natheight") != opts.end())
2077 numberOfbbOptions++;
2078 if (numberOfbbOptions == 2)
2079 os << "\tBoundingBox 0bp 0bp "
2080 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2081 else if (numberOfbbOptions > 0)
2082 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2083 ostringstream special;
2084 if (opts.find("hiresbb") != opts.end())
2085 special << "hiresbb,";
2086 if (opts.find("trim") != opts.end())
2088 if (opts.find("viewport") != opts.end())
2089 special << "viewport=" << opts["viewport"] << ',';
2090 if (opts.find("totalheight") != opts.end())
2091 special << "totalheight=" << opts["totalheight"] << ',';
2092 if (opts.find("type") != opts.end())
2093 special << "type=" << opts["type"] << ',';
2094 if (opts.find("ext") != opts.end())
2095 special << "ext=" << opts["ext"] << ',';
2096 if (opts.find("read") != opts.end())
2097 special << "read=" << opts["read"] << ',';
2098 if (opts.find("command") != opts.end())
2099 special << "command=" << opts["command"] << ',';
2100 string s_special = special.str();
2101 if (!s_special.empty()) {
2102 // We had special arguments. Remove the trailing ','.
2103 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2105 // TODO: Handle the unknown settings better.
2106 // Warn about invalid options.
2107 // Check whether some option was given twice.
2111 else if (t.cs() == "footnote" ||
2112 (t.cs() == "thanks" && context.layout->intitle)) {
2114 context.check_layout(os);
2115 begin_inset(os, "Foot\n");
2116 os << "status collapsed\n\n";
2117 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2121 else if (t.cs() == "marginpar") {
2123 context.check_layout(os);
2124 begin_inset(os, "Marginal\n");
2125 os << "status collapsed\n\n";
2126 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2130 else if (t.cs() == "ensuremath") {
2132 context.check_layout(os);
2133 string const s = p.verbatim_item();
2134 //FIXME: this never triggers in UTF8
2135 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2138 handle_ert(os, "\\ensuremath{" + s + "}",
2142 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2143 // FIXME: Somehow prevent title layouts if
2144 // "maketitle" was not found
2146 skip_spaces_braces(p);
2149 else if (t.cs() == "tableofcontents") {
2150 context.check_layout(os);
2151 begin_command_inset(os, "toc", "tableofcontents");
2153 skip_spaces_braces(p);
2156 else if (t.cs() == "listoffigures") {
2157 context.check_layout(os);
2158 begin_inset(os, "FloatList figure\n");
2160 skip_spaces_braces(p);
2163 else if (t.cs() == "listoftables") {
2164 context.check_layout(os);
2165 begin_inset(os, "FloatList table\n");
2167 skip_spaces_braces(p);
2170 else if (t.cs() == "listof") {
2171 p.skip_spaces(true);
2172 string const name = p.get_token().cs();
2173 if (context.textclass.floats().typeExist(name)) {
2174 context.check_layout(os);
2175 begin_inset(os, "FloatList ");
2178 p.get_token(); // swallow second arg
2180 handle_ert(os, "\\listof{" + name + "}", context);
2183 else if (t.cs() == "textrm")
2184 parse_text_attributes(p, os, FLAG_ITEM, outer,
2185 context, "\\family",
2186 context.font.family, "roman");
2188 else if (t.cs() == "textsf")
2189 parse_text_attributes(p, os, FLAG_ITEM, outer,
2190 context, "\\family",
2191 context.font.family, "sans");
2193 else if (t.cs() == "texttt")
2194 parse_text_attributes(p, os, FLAG_ITEM, outer,
2195 context, "\\family",
2196 context.font.family, "typewriter");
2198 else if (t.cs() == "textmd")
2199 parse_text_attributes(p, os, FLAG_ITEM, outer,
2200 context, "\\series",
2201 context.font.series, "medium");
2203 else if (t.cs() == "textbf")
2204 parse_text_attributes(p, os, FLAG_ITEM, outer,
2205 context, "\\series",
2206 context.font.series, "bold");
2208 else if (t.cs() == "textup")
2209 parse_text_attributes(p, os, FLAG_ITEM, outer,
2211 context.font.shape, "up");
2213 else if (t.cs() == "textit")
2214 parse_text_attributes(p, os, FLAG_ITEM, outer,
2216 context.font.shape, "italic");
2218 else if (t.cs() == "textsl")
2219 parse_text_attributes(p, os, FLAG_ITEM, outer,
2221 context.font.shape, "slanted");
2223 else if (t.cs() == "textsc")
2224 parse_text_attributes(p, os, FLAG_ITEM, outer,
2226 context.font.shape, "smallcaps");
2228 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2229 context.check_layout(os);
2230 TeXFont oldFont = context.font;
2231 context.font.init();
2232 context.font.size = oldFont.size;
2233 os << "\n\\family " << context.font.family << "\n";
2234 os << "\n\\series " << context.font.series << "\n";
2235 os << "\n\\shape " << context.font.shape << "\n";
2236 if (t.cs() == "textnormal") {
2237 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2238 output_font_change(os, context.font, oldFont);
2239 context.font = oldFont;
2241 eat_whitespace(p, os, context, false);
2244 else if (t.cs() == "textcolor") {
2245 // scheme is \textcolor{color name}{text}
2246 string const color = p.verbatim_item();
2247 // we only support the predefined colors of the color package
2248 if (color == "black" || color == "blue" || color == "cyan"
2249 || color == "green" || color == "magenta" || color == "red"
2250 || color == "white" || color == "yellow") {
2251 context.check_layout(os);
2252 os << "\n\\color " << color << "\n";
2253 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2254 context.check_layout(os);
2255 os << "\n\\color inherit\n";
2257 // for custom defined colors
2258 handle_ert(os, t.asInput() + "{" + color + "}", context);
2261 else if (t.cs() == "underbar") {
2262 // Do NOT handle \underline.
2263 // \underbar cuts through y, g, q, p etc.,
2264 // \underline does not.
2265 context.check_layout(os);
2266 os << "\n\\bar under\n";
2267 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2268 context.check_layout(os);
2269 os << "\n\\bar default\n";
2272 else if (t.cs() == "emph" || t.cs() == "noun") {
2273 context.check_layout(os);
2274 os << "\n\\" << t.cs() << " on\n";
2275 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2276 context.check_layout(os);
2277 os << "\n\\" << t.cs() << " default\n";
2280 else if (t.cs() == "lyxline") {
2281 context.check_layout(os);
2285 else if (is_known(t.cs(), known_phrases) ||
2286 (t.cs() == "protect" &&
2287 p.next_token().cat() == catEscape &&
2288 is_known(p.next_token().cs(), known_phrases))) {
2289 // LyX sometimes puts a \protect in front, so we have to ignore it
2290 // FIXME: This needs to be changed when bug 4752 is fixed.
2291 char const * const * where = is_known(
2292 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2294 context.check_layout(os);
2295 os << known_coded_phrases[where - known_phrases];
2296 skip_spaces_braces(p);
2299 else if (is_known(t.cs(), known_ref_commands)) {
2300 context.check_layout(os);
2301 begin_command_inset(os, "ref", t.cs());
2302 // LyX cannot handle newlines in a latex command
2303 // FIXME: Move the substitution into parser::getOpt()?
2304 os << subst(p.getOpt(), "\n", " ");
2305 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2309 else if (use_natbib &&
2310 is_known(t.cs(), known_natbib_commands) &&
2311 ((t.cs() != "citefullauthor" &&
2312 t.cs() != "citeyear" &&
2313 t.cs() != "citeyearpar") ||
2314 p.next_token().asInput() != "*")) {
2315 context.check_layout(os);
2316 string command = t.cs();
2317 if (p.next_token().asInput() == "*") {
2321 if (command == "citefullauthor")
2322 // alternative name for "\\citeauthor*"
2323 command = "citeauthor*";
2325 // text before the citation
2327 // text after the citation
2329 get_cite_arguments(p, true, before, after);
2331 if (command == "cite") {
2332 // \cite without optional argument means
2333 // \citet, \cite with at least one optional
2334 // argument means \citep.
2335 if (before.empty() && after.empty())
2340 if (before.empty() && after == "[]")
2341 // avoid \citet[]{a}
2343 else if (before == "[]" && after == "[]") {
2344 // avoid \citet[][]{a}
2348 // remove the brackets around after and before
2349 if (!after.empty()) {
2351 after.erase(after.length() - 1, 1);
2352 // LyX cannot handle newlines in the parameter
2353 after = subst(after, "\n", " ");
2355 if (!before.empty()) {
2357 before.erase(before.length() - 1, 1);
2358 // LyX cannot handle newlines in the parameter
2359 before = subst(before, "\n", " ");
2361 begin_command_inset(os, "citation", command);
2362 os << "after " << '"' << after << '"' << "\n";
2363 os << "before " << '"' << before << '"' << "\n";
2364 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2368 else if (use_jurabib &&
2369 is_known(t.cs(), known_jurabib_commands) &&
2370 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2371 context.check_layout(os);
2372 string command = t.cs();
2373 if (p.next_token().asInput() == "*") {
2377 char argumentOrder = '\0';
2378 vector<string> const & options = used_packages["jurabib"];
2379 if (find(options.begin(), options.end(),
2380 "natbiborder") != options.end())
2381 argumentOrder = 'n';
2382 else if (find(options.begin(), options.end(),
2383 "jurabiborder") != options.end())
2384 argumentOrder = 'j';
2386 // text before the citation
2388 // text after the citation
2390 get_cite_arguments(p, argumentOrder != 'j', before, after);
2392 string const citation = p.verbatim_item();
2393 if (!before.empty() && argumentOrder == '\0') {
2394 cerr << "Warning: Assuming argument order "
2395 "of jurabib version 0.6 for\n'"
2396 << command << before << after << '{'
2397 << citation << "}'.\n"
2398 "Add 'jurabiborder' to the jurabib "
2399 "package options if you used an\n"
2400 "earlier jurabib version." << endl;
2402 if (!after.empty()) {
2404 after.erase(after.length() - 1, 1);
2406 if (!before.empty()) {
2408 before.erase(before.length() - 1, 1);
2410 begin_command_inset(os, "citation", command);
2411 os << "after " << '"' << after << '"' << "\n";
2412 os << "before " << '"' << before << '"' << "\n";
2413 os << "key " << '"' << citation << '"' << "\n";
2417 else if (t.cs() == "cite"
2418 || t.cs() == "nocite") {
2419 context.check_layout(os);
2420 // LyX cannot handle newlines in a latex command
2421 string after = subst(p.getOptContent(), "\n", " ");
2422 string key = subst(p.verbatim_item(), "\n", " ");
2423 // store the case that it is "\nocite{*}" to use it later for
2426 begin_command_inset(os, "citation", t.cs());
2427 os << "after " << '"' << after << '"' << "\n";
2428 os << "key " << '"' << key << '"' << "\n";
2430 } else if (t.cs() == "nocite")
2434 else if (t.cs() == "index") {
2435 context.check_layout(os);
2436 begin_inset(os, "Index\n");
2437 os << "status collapsed\n";
2438 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2442 else if (t.cs() == "nomenclature") {
2443 context.check_layout(os);
2444 begin_command_inset(os, "nomenclature", "nomenclature");
2445 // LyX cannot handle newlines in a latex command
2446 string prefix = subst(p.getOptContent(), "\n", " ");
2447 if (!prefix.empty())
2448 os << "prefix " << '"' << prefix << '"' << "\n";
2449 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2450 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2454 else if (t.cs() == "label") {
2455 context.check_layout(os);
2456 begin_command_inset(os, "label", "label");
2457 // LyX cannot handle newlines in a latex command
2458 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2462 else if (t.cs() == "printindex") {
2463 context.check_layout(os);
2464 begin_command_inset(os, "index_print", "printindex");
2466 skip_spaces_braces(p);
2469 else if (t.cs() == "printnomenclature") {
2470 context.check_layout(os);
2471 begin_command_inset(os, "nomencl_print", "printnomenclature");
2473 skip_spaces_braces(p);
2476 else if (LYX_FORMAT >= 408 &&
2477 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2478 context.check_layout(os);
2479 begin_inset(os, "script ");
2480 os << t.cs().substr(4) << '\n';
2481 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2485 else if (is_known(t.cs(), known_quotes)) {
2486 char const * const * where = is_known(t.cs(), known_quotes);
2487 context.check_layout(os);
2488 begin_inset(os, "Quotes ");
2489 os << known_coded_quotes[where - known_quotes];
2491 // LyX adds {} after the quote, so we have to eat
2492 // spaces here if there are any before a possible
2494 eat_whitespace(p, os, context, false);
2498 else if (is_known(t.cs(), known_sizes) &&
2499 context.new_layout_allowed) {
2500 char const * const * where = is_known(t.cs(), known_sizes);
2501 context.check_layout(os);
2502 TeXFont const oldFont = context.font;
2503 context.font.size = known_coded_sizes[where - known_sizes];
2504 output_font_change(os, oldFont, context.font);
2505 eat_whitespace(p, os, context, false);
2508 else if (is_known(t.cs(), known_font_families) &&
2509 context.new_layout_allowed) {
2510 char const * const * where =
2511 is_known(t.cs(), known_font_families);
2512 context.check_layout(os);
2513 TeXFont const oldFont = context.font;
2514 context.font.family =
2515 known_coded_font_families[where - known_font_families];
2516 output_font_change(os, oldFont, context.font);
2517 eat_whitespace(p, os, context, false);
2520 else if (is_known(t.cs(), known_font_series) &&
2521 context.new_layout_allowed) {
2522 char const * const * where =
2523 is_known(t.cs(), known_font_series);
2524 context.check_layout(os);
2525 TeXFont const oldFont = context.font;
2526 context.font.series =
2527 known_coded_font_series[where - known_font_series];
2528 output_font_change(os, oldFont, context.font);
2529 eat_whitespace(p, os, context, false);
2532 else if (is_known(t.cs(), known_font_shapes) &&
2533 context.new_layout_allowed) {
2534 char const * const * where =
2535 is_known(t.cs(), known_font_shapes);
2536 context.check_layout(os);
2537 TeXFont const oldFont = context.font;
2538 context.font.shape =
2539 known_coded_font_shapes[where - known_font_shapes];
2540 output_font_change(os, oldFont, context.font);
2541 eat_whitespace(p, os, context, false);
2543 else if (is_known(t.cs(), known_old_font_families) &&
2544 context.new_layout_allowed) {
2545 char const * const * where =
2546 is_known(t.cs(), known_old_font_families);
2547 context.check_layout(os);
2548 TeXFont const oldFont = context.font;
2549 context.font.init();
2550 context.font.size = oldFont.size;
2551 context.font.family =
2552 known_coded_font_families[where - known_old_font_families];
2553 output_font_change(os, oldFont, context.font);
2554 eat_whitespace(p, os, context, false);
2557 else if (is_known(t.cs(), known_old_font_series) &&
2558 context.new_layout_allowed) {
2559 char const * const * where =
2560 is_known(t.cs(), known_old_font_series);
2561 context.check_layout(os);
2562 TeXFont const oldFont = context.font;
2563 context.font.init();
2564 context.font.size = oldFont.size;
2565 context.font.series =
2566 known_coded_font_series[where - known_old_font_series];
2567 output_font_change(os, oldFont, context.font);
2568 eat_whitespace(p, os, context, false);
2571 else if (is_known(t.cs(), known_old_font_shapes) &&
2572 context.new_layout_allowed) {
2573 char const * const * where =
2574 is_known(t.cs(), known_old_font_shapes);
2575 context.check_layout(os);
2576 TeXFont const oldFont = context.font;
2577 context.font.init();
2578 context.font.size = oldFont.size;
2579 context.font.shape =
2580 known_coded_font_shapes[where - known_old_font_shapes];
2581 output_font_change(os, oldFont, context.font);
2582 eat_whitespace(p, os, context, false);
2585 else if (t.cs() == "selectlanguage") {
2586 context.check_layout(os);
2587 // save the language for the case that a
2588 // \foreignlanguage is used
2590 context.font.language = babel2lyx(p.verbatim_item());
2591 os << "\n\\lang " << context.font.language << "\n";
2594 else if (t.cs() == "foreignlanguage") {
2595 string const lang = babel2lyx(p.verbatim_item());
2596 parse_text_attributes(p, os, FLAG_ITEM, outer,
2598 context.font.language, lang);
2601 else if (t.cs() == "inputencoding") {
2602 // nothing to write here
2603 string const enc = subst(p.verbatim_item(), "\n", " ");
2607 else if (t.cs() == "ldots") {
2608 context.check_layout(os);
2609 os << "\\SpecialChar \\ldots{}\n";
2610 skip_spaces_braces(p);
2613 else if (t.cs() == "lyxarrow") {
2614 context.check_layout(os);
2615 os << "\\SpecialChar \\menuseparator\n";
2616 skip_spaces_braces(p);
2619 else if (t.cs() == "textcompwordmark") {
2620 context.check_layout(os);
2621 os << "\\SpecialChar \\textcompwordmark{}\n";
2622 skip_spaces_braces(p);
2625 else if (t.cs() == "slash") {
2626 context.check_layout(os);
2627 os << "\\SpecialChar \\slash{}\n";
2628 skip_spaces_braces(p);
2631 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2632 context.check_layout(os);
2633 os << "\\SpecialChar \\nobreakdash-\n";
2637 else if (t.cs() == "textquotedbl") {
2638 context.check_layout(os);
2643 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2644 context.check_layout(os);
2645 os << "\\SpecialChar \\@.\n";
2649 else if (t.cs() == "-") {
2650 context.check_layout(os);
2651 os << "\\SpecialChar \\-\n";
2654 else if (t.cs() == "textasciitilde") {
2655 context.check_layout(os);
2657 skip_spaces_braces(p);
2660 else if (t.cs() == "textasciicircum") {
2661 context.check_layout(os);
2663 skip_spaces_braces(p);
2666 else if (t.cs() == "textbackslash") {
2667 context.check_layout(os);
2668 os << "\n\\backslash\n";
2669 skip_spaces_braces(p);
2672 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2673 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2675 context.check_layout(os);
2679 else if (t.cs() == "char") {
2680 context.check_layout(os);
2681 if (p.next_token().character() == '`') {
2683 if (p.next_token().cs() == "\"") {
2688 handle_ert(os, "\\char`", context);
2691 handle_ert(os, "\\char", context);
2695 else if (t.cs() == "verb") {
2696 context.check_layout(os);
2697 char const delimiter = p.next_token().character();
2698 string const arg = p.getArg(delimiter, delimiter);
2700 oss << "\\verb" << delimiter << arg << delimiter;
2701 handle_ert(os, oss.str(), context);
2704 // Problem: \= creates a tabstop inside the tabbing environment
2705 // and else an accent. In the latter case we really would want
2706 // \={o} instead of \= o.
2707 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2708 handle_ert(os, t.asInput(), context);
2710 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2711 else if (t.cs().size() == 1
2712 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2713 context.check_layout(os);
2714 // try to see whether the string is in unicodesymbols
2716 string command = t.asInput() + "{"
2717 + trim(p.verbatim_item())
2719 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2722 cerr << "When parsing " << command
2723 << ", result is " << to_utf8(s)
2724 << "+" << to_utf8(rem) << endl;
2727 // we did not find a non-ert version
2728 handle_ert(os, command, context);
2731 else if (t.cs() == "\\") {
2732 context.check_layout(os);
2734 handle_ert(os, "\\\\" + p.getOpt(), context);
2735 else if (p.next_token().asInput() == "*") {
2737 // getOpt() eats the following space if there
2738 // is no optional argument, but that is OK
2739 // here since it has no effect in the output.
2740 handle_ert(os, "\\\\*" + p.getOpt(), context);
2743 begin_inset(os, "Newline newline");
2748 else if (t.cs() == "newline" ||
2749 (t.cs() == "linebreak" && !p.hasOpt())) {
2750 context.check_layout(os);
2751 begin_inset(os, "Newline ");
2754 skip_spaces_braces(p);
2757 else if (t.cs() == "input" || t.cs() == "include"
2758 || t.cs() == "verbatiminput") {
2759 string name = t.cs();
2760 if (t.cs() == "verbatiminput"
2761 && p.next_token().asInput() == "*")
2762 name += p.get_token().asInput();
2763 context.check_layout(os);
2764 string filename(normalize_filename(p.getArg('{', '}')));
2765 string const path = getMasterFilePath();
2766 // We want to preserve relative / absolute filenames,
2767 // therefore path is only used for testing
2768 if ((t.cs() == "include" || t.cs() == "input") &&
2769 !makeAbsPath(filename, path).exists()) {
2770 // The file extension is probably missing.
2771 // Now try to find it out.
2772 string const tex_name =
2773 find_file(filename, path,
2774 known_tex_extensions);
2775 if (!tex_name.empty())
2776 filename = tex_name;
2778 bool external = false;
2780 if (makeAbsPath(filename, path).exists()) {
2781 string const abstexname =
2782 makeAbsPath(filename, path).absFileName();
2783 string const abslyxname =
2784 changeExtension(abstexname, ".lyx");
2785 string const absfigname =
2786 changeExtension(abstexname, ".fig");
2787 fix_relative_filename(filename);
2788 string const lyxname =
2789 changeExtension(filename, ".lyx");
2791 external = FileName(absfigname).exists();
2792 if (t.cs() == "input") {
2793 string const ext = getExtension(abstexname);
2795 // Combined PS/LaTeX:
2796 // x.eps, x.pstex_t (old xfig)
2797 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2798 FileName const absepsname(
2799 changeExtension(abstexname, ".eps"));
2800 FileName const abspstexname(
2801 changeExtension(abstexname, ".pstex"));
2802 bool const xfigeps =
2803 (absepsname.exists() ||
2804 abspstexname.exists()) &&
2807 // Combined PDF/LaTeX:
2808 // x.pdf, x.pdftex_t (old xfig)
2809 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2810 FileName const abspdfname(
2811 changeExtension(abstexname, ".pdf"));
2812 bool const xfigpdf =
2813 abspdfname.exists() &&
2814 (ext == "pdftex_t" || ext == "pdf_t");
2818 // Combined PS/PDF/LaTeX:
2819 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2820 string const absbase2(
2821 removeExtension(abstexname) + "_pspdftex");
2822 FileName const abseps2name(
2823 addExtension(absbase2, ".eps"));
2824 FileName const abspdf2name(
2825 addExtension(absbase2, ".pdf"));
2826 bool const xfigboth =
2827 abspdf2name.exists() &&
2828 abseps2name.exists() && ext == "pspdftex";
2830 xfig = xfigpdf || xfigeps || xfigboth;
2831 external = external && xfig;
2834 outname = changeExtension(filename, ".fig");
2836 // Don't try to convert, the result
2837 // would be full of ERT.
2839 } else if (t.cs() != "verbatiminput" &&
2840 tex2lyx(abstexname, FileName(abslyxname),
2847 cerr << "Warning: Could not find included file '"
2848 << filename << "'." << endl;
2852 begin_inset(os, "External\n");
2853 os << "\ttemplate XFig\n"
2854 << "\tfilename " << outname << '\n';
2856 begin_command_inset(os, "include", name);
2857 os << "preview false\n"
2858 "filename \"" << outname << "\"\n";
2863 else if (t.cs() == "bibliographystyle") {
2864 // store new bibliographystyle
2865 bibliographystyle = p.verbatim_item();
2866 // If any other command than \bibliography and
2867 // \nocite{*} follows, we need to output the style
2868 // (because it might be used by that command).
2869 // Otherwise, it will automatically be output by LyX.
2872 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
2873 if (t2.cat() == catBegin)
2875 if (t2.cat() != catEscape)
2877 if (t2.cs() == "nocite") {
2878 if (p.getArg('{', '}') == "*")
2880 } else if (t2.cs() == "bibliography")
2887 "\\bibliographystyle{" + bibliographystyle + '}',
2892 else if (t.cs() == "bibliography") {
2893 context.check_layout(os);
2894 begin_command_inset(os, "bibtex", "bibtex");
2895 if (!btprint.empty()) {
2896 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2897 // clear the string because the next BibTeX inset can be without the
2898 // \nocite{*} option
2901 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2902 // Do we have a bibliographystyle set?
2903 if (!bibliographystyle.empty())
2904 os << "options " << '"' << bibliographystyle << '"' << "\n";
2908 else if (t.cs() == "parbox")
2909 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
2911 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
2912 t.cs() == "shadowbox" || t.cs() == "doublebox")
2913 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
2915 else if (t.cs() == "framebox") {
2916 string special = p.getOpt();
2917 special += p.getOpt();
2918 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
2921 //\makebox() is part of the picture environment and different from \makebox{}
2922 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2923 else if (t.cs() == "makebox") {
2924 string arg = t.asInput();
2925 if (p.next_token().character() == '(')
2926 //the syntax is: \makebox(x,y)[position]{content}
2927 arg += p.getFullParentheseArg();
2929 //the syntax is: \makebox[width][position]{content}
2930 arg += p.getFullOpt();
2931 handle_ert(os, arg + p.getFullOpt(), context);
2934 else if (t.cs() == "smallskip" ||
2935 t.cs() == "medskip" ||
2936 t.cs() == "bigskip" ||
2937 t.cs() == "vfill") {
2938 context.check_layout(os);
2939 begin_inset(os, "VSpace ");
2942 skip_spaces_braces(p);
2945 else if (is_known(t.cs(), known_spaces)) {
2946 char const * const * where = is_known(t.cs(), known_spaces);
2947 context.check_layout(os);
2948 begin_inset(os, "space ");
2949 os << '\\' << known_coded_spaces[where - known_spaces]
2952 // LaTeX swallows whitespace after all spaces except
2953 // "\\,". We have to do that here, too, because LyX
2954 // adds "{}" which would make the spaces significant.
2956 eat_whitespace(p, os, context, false);
2957 // LyX adds "{}" after all spaces except "\\ " and
2958 // "\\,", so we have to remove "{}".
2959 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2960 // remove the braces after "\\,", too.
2965 else if (t.cs() == "newpage" ||
2966 (t.cs() == "pagebreak" && !p.hasOpt()) ||
2967 t.cs() == "clearpage" ||
2968 t.cs() == "cleardoublepage") {
2969 context.check_layout(os);
2970 begin_inset(os, "Newpage ");
2973 skip_spaces_braces(p);
2976 else if (t.cs() == "DeclareRobustCommand" ||
2977 t.cs() == "DeclareRobustCommandx" ||
2978 t.cs() == "newcommand" ||
2979 t.cs() == "newcommandx" ||
2980 t.cs() == "providecommand" ||
2981 t.cs() == "providecommandx" ||
2982 t.cs() == "renewcommand" ||
2983 t.cs() == "renewcommandx") {
2984 // DeclareRobustCommand, DeclareRobustCommandx,
2985 // providecommand and providecommandx could be handled
2986 // by parse_command(), but we need to call
2987 // add_known_command() here.
2988 string name = t.asInput();
2989 if (p.next_token().asInput() == "*") {
2990 // Starred form. Eat '*'
2994 string const command = p.verbatim_item();
2995 string const opt1 = p.getOpt();
2996 string const opt2 = p.getFullOpt();
2997 add_known_command(command, opt1, !opt2.empty());
2998 string const ert = name + '{' + command + '}' +
3000 '{' + p.verbatim_item() + '}';
3002 if (t.cs() == "DeclareRobustCommand" ||
3003 t.cs() == "DeclareRobustCommandx" ||
3004 t.cs() == "providecommand" ||
3005 t.cs() == "providecommandx" ||
3006 name[name.length()-1] == '*')
3007 handle_ert(os, ert, context);
3009 context.check_layout(os);
3010 begin_inset(os, "FormulaMacro");
3016 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3017 // let could be handled by parse_command(),
3018 // but we need to call add_known_command() here.
3019 string ert = t.asInput();
3022 if (p.next_token().cat() == catBegin) {
3023 name = p.verbatim_item();
3024 ert += '{' + name + '}';
3026 name = p.verbatim_item();
3031 if (p.next_token().cat() == catBegin) {
3032 command = p.verbatim_item();
3033 ert += '{' + command + '}';
3035 command = p.verbatim_item();
3038 // If command is known, make name known too, to parse
3039 // its arguments correctly. For this reason we also
3040 // have commands in syntax.default that are hardcoded.
3041 CommandMap::iterator it = known_commands.find(command);
3042 if (it != known_commands.end())
3043 known_commands[t.asInput()] = it->second;
3044 handle_ert(os, ert, context);
3047 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3048 bool starred = false;
3049 if (p.next_token().asInput() == "*") {
3053 string name = t.asInput();
3054 string const length = p.verbatim_item();
3057 bool valid = splitLatexLength(length, valstring, unit);
3058 bool known_hspace = false;
3059 bool known_vspace = false;
3060 bool known_unit = false;
3063 istringstream iss(valstring);
3066 if (t.cs()[0] == 'h') {
3067 if (unit == "\\fill") {
3072 known_hspace = true;
3075 if (unit == "\\smallskipamount") {
3077 known_vspace = true;
3078 } else if (unit == "\\medskipamount") {
3080 known_vspace = true;
3081 } else if (unit == "\\bigskipamount") {
3083 known_vspace = true;
3084 } else if (unit == "\\fill") {
3086 known_vspace = true;
3090 if (!known_hspace && !known_vspace) {
3091 switch (unitFromString(unit)) {
3112 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3113 // Literal horizontal length or known variable
3114 context.check_layout(os);
3115 begin_inset(os, "space ");
3123 if (known_unit && !known_hspace)
3125 << translate_len(length);
3127 } else if (known_unit || known_vspace) {
3128 // Literal vertical length or known variable
3129 context.check_layout(os);
3130 begin_inset(os, "VSpace ");
3138 // LyX can't handle other length variables in Inset VSpace/space
3143 handle_ert(os, name + '{' + unit + '}', context);
3144 else if (value == -1.0)
3145 handle_ert(os, name + "{-" + unit + '}', context);
3147 handle_ert(os, name + '{' + valstring + unit + '}', context);
3149 handle_ert(os, name + '{' + length + '}', context);
3153 // The single '=' is meant here.
3154 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3156 context.check_layout(os);
3157 begin_inset(os, "Flex ");
3158 os << to_utf8(newinsetlayout->name()) << '\n'
3159 << "status collapsed\n";
3160 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3165 // try to see whether the string is in unicodesymbols
3166 // Only use text mode commands, since we are in text mode here,
3167 // and math commands may be invalid (bug 6797)
3169 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3170 rem, Encodings::TEXT_CMD);
3173 cerr << "When parsing " << t.cs()
3174 << ", result is " << to_utf8(s)
3175 << "+" << to_utf8(rem) << endl;
3176 context.check_layout(os);
3178 skip_spaces_braces(p);
3180 //cerr << "#: " << t << " mode: " << mode << endl;
3181 // heuristic: read up to next non-nested space
3183 string s = t.asInput();
3184 string z = p.verbatim_item();
3185 while (p.good() && z != " " && z.size()) {
3186 //cerr << "read: " << z << endl;
3188 z = p.verbatim_item();
3190 cerr << "found ERT: " << s << endl;
3191 handle_ert(os, s + ' ', context);
3194 string name = t.asInput();
3195 if (p.next_token().asInput() == "*") {
3196 // Starred commands like \vspace*{}
3197 p.get_token(); // Eat '*'
3200 if (!parse_command(name, p, os, outer, context))
3201 handle_ert(os, name, context);
3205 if (flags & FLAG_LEAVE) {
3206 flags &= ~FLAG_LEAVE;