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"
26 #include "support/lassert.h"
27 #include "support/convert.h"
28 #include "support/FileName.h"
29 #include "support/filetools.h"
30 #include "support/lstrings.h"
39 using namespace lyx::support;
44 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
45 Context const & context, InsetLayout const * layout)
47 bool const forcePlainLayout =
48 layout ? layout->forcePlainLayout() : false;
49 Context newcontext(true, context.textclass);
51 newcontext.layout = &context.textclass.plainLayout();
53 newcontext.font = context.font;
54 parse_text(p, os, flags, outer, newcontext);
55 newcontext.check_end_layout(os);
61 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
62 Context const & context, string const & name)
64 InsetLayout const * layout = 0;
65 DocumentClass::InsetLayouts::const_iterator it =
66 context.textclass.insetLayouts().find(from_ascii(name));
67 if (it != context.textclass.insetLayouts().end())
68 layout = &(it->second);
69 parse_text_in_inset(p, os, flags, outer, context, layout);
72 /// parses a paragraph snippet, useful for example for \\emph{...}
73 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
76 Context newcontext(context);
77 // Don't inherit the paragraph-level extra stuff
78 newcontext.par_extra_stuff.clear();
79 parse_text(p, os, flags, outer, newcontext);
80 // Make sure that we don't create invalid .lyx files
81 context.need_layout = newcontext.need_layout;
82 context.need_end_layout = newcontext.need_end_layout;
87 * Thin wrapper around parse_text_snippet() using a string.
89 * We completely ignore \c context.need_layout and \c context.need_end_layout,
90 * because our return value is not used directly (otherwise the stream version
91 * of parse_text_snippet() could be used). That means that the caller needs
92 * to do layout management manually.
93 * This is intended to parse text that does not create any layout changes.
95 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
98 Context newcontext(context);
99 newcontext.need_layout = false;
100 newcontext.need_end_layout = false;
101 newcontext.new_layout_allowed = false;
102 // Avoid warning by Context::~Context()
103 newcontext.par_extra_stuff.clear();
105 parse_text_snippet(p, os, flags, outer, newcontext);
110 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
111 "vpageref", "prettyref", "eqref", 0 };
113 char const * const known_coded_ref_commands[] = { "ref", "pageref", "vref",
114 "vpageref", "formatted", "eqref", 0 };
118 * The starred forms are also known except for "citefullauthor",
119 * "citeyear" and "citeyearpar".
121 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
122 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
123 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
127 * No starred form other than "cite*" known.
129 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
130 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
131 // jurabib commands not (yet) supported by LyX:
133 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
134 // "footciteauthor", "footciteyear", "footciteyearpar",
135 "citefield", "citetitle", 0 };
137 /// LaTeX names for quotes
138 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
139 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
140 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
141 "guilsinglleft", "frq", "guilsinglright", 0};
143 /// the same as known_quotes with .lyx names
144 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
145 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
146 "gld", "grd", "gls", "ers", "fls",
147 "fls", "frs", "frs", 0};
149 /// LaTeX names for font sizes
150 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
153 /// the same as known_sizes with .lyx names
154 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
155 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
157 /// LaTeX 2.09 names for font families
158 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
160 /// LaTeX names for font families
161 char const * const known_font_families[] = { "rmfamily", "sffamily",
164 /// the same as known_old_font_families and known_font_families with .lyx names
165 char const * const known_coded_font_families[] = { "roman", "sans",
168 /// LaTeX 2.09 names for font series
169 char const * const known_old_font_series[] = { "bf", 0};
171 /// LaTeX names for font series
172 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
174 /// the same as known_old_font_series and known_font_series with .lyx names
175 char const * const known_coded_font_series[] = { "bold", "medium", 0};
177 /// LaTeX 2.09 names for font shapes
178 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
180 /// LaTeX names for font shapes
181 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
184 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
185 char const * const known_coded_font_shapes[] = { "italic", "slanted",
186 "smallcaps", "up", 0};
189 * Graphics file extensions known by the dvips driver of the graphics package.
190 * These extensions are used to complete the filename of an included
191 * graphics file if it does not contain an extension.
192 * The order must be the same that latex uses to find a file, because we
193 * will use the first extension that matches.
194 * This is only an approximation for the common cases. If we would want to
195 * do it right in all cases, we would need to know which graphics driver is
196 * used and know the extensions of every driver of the graphics package.
198 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
199 "ps.gz", "eps.Z", "ps.Z", 0};
202 * Graphics file extensions known by the pdftex driver of the graphics package.
203 * \sa known_dvips_graphics_formats
205 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
209 * Known file extensions for TeX files as used by \\include.
211 char const * const known_tex_extensions[] = {"tex", 0};
213 /// spaces known by InsetSpace
214 char const * const known_spaces[] = { " ", "space", ",",
215 "thinspace", "quad", "qquad", "enspace", "enskip",
216 "negthinspace", "negmedspace", "negthickspace", "textvisiblespace",
217 "hfill", "dotfill", "hrulefill", "leftarrowfill", "rightarrowfill",
218 "upbracefill", "downbracefill", 0};
220 /// the same as known_spaces with .lyx names
221 char const * const known_coded_spaces[] = { "space{}", "space{}",
222 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
223 "negthinspace{}", "negmedspace{}", "negthickspace{}", "textvisiblespace{}",
224 "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}", "rightarrowfill{}",
225 "upbracefill{}", "downbracefill{}", 0};
227 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
228 /// them in ERT. "LaTeXe" must come before "LaTeX"!
229 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
230 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
231 int const known_phrase_lengths[] = {3, 5, 7, 0};
233 // string to store the float type to be able to determine the type of subfloats
234 string float_type = "";
237 /// splits "x=z, y=b" into a map and an ordered keyword vector
238 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
243 keys.resize(v.size());
244 for (size_t i = 0; i < v.size(); ++i) {
245 size_t const pos = v[i].find('=');
246 string const index = trimSpaceAndEol(v[i].substr(0, pos));
247 string const value = trimSpaceAndEol(v[i].substr(pos + 1, string::npos));
255 * Split a LaTeX length into value and unit.
256 * The latter can be a real unit like "pt", or a latex length variable
257 * like "\textwidth". The unit may contain additional stuff like glue
258 * lengths, but we don't care, because such lengths are ERT anyway.
259 * \returns true if \p value and \p unit are valid.
261 bool splitLatexLength(string const & len, string & value, string & unit)
265 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
266 //'4,5' is a valid LaTeX length number. Change it to '4.5'
267 string const length = subst(len, ',', '.');
268 if (i == string::npos)
271 if (len[0] == '\\') {
272 // We had something like \textwidth without a factor
278 value = trimSpaceAndEol(string(length, 0, i));
282 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
283 if (contains(len, '\\'))
284 unit = trimSpaceAndEol(string(len, i));
286 unit = ascii_lowercase(trimSpaceAndEol(string(len, i)));
291 /// A simple function to translate a latex length to something LyX can
292 /// understand. Not perfect, but rather best-effort.
293 bool translate_len(string const & length, string & valstring, string & unit)
295 if (!splitLatexLength(length, valstring, unit))
297 // LyX uses percent values
299 istringstream iss(valstring);
304 string const percentval = oss.str();
306 if (unit.empty() || unit[0] != '\\')
308 string::size_type const i = unit.find(' ');
309 string const endlen = (i == string::npos) ? string() : string(unit, i);
310 if (unit == "\\textwidth") {
311 valstring = percentval;
312 unit = "text%" + endlen;
313 } else if (unit == "\\columnwidth") {
314 valstring = percentval;
315 unit = "col%" + endlen;
316 } else if (unit == "\\paperwidth") {
317 valstring = percentval;
318 unit = "page%" + endlen;
319 } else if (unit == "\\linewidth") {
320 valstring = percentval;
321 unit = "line%" + endlen;
322 } else if (unit == "\\paperheight") {
323 valstring = percentval;
324 unit = "pheight%" + endlen;
325 } else if (unit == "\\textheight") {
326 valstring = percentval;
327 unit = "theight%" + endlen;
335 string translate_len(string const & length)
339 if (translate_len(length, value, unit))
341 // If the input is invalid, return what we have.
349 * Translates a LaTeX length into \p value, \p unit and
350 * \p special parts suitable for a box inset.
351 * The difference from translate_len() is that a box inset knows about
352 * some special "units" that are stored in \p special.
354 void translate_box_len(string const & length, string & value, string & unit, string & special)
356 if (translate_len(length, value, unit)) {
357 if (unit == "\\height" || unit == "\\depth" ||
358 unit == "\\totalheight" || unit == "\\width") {
359 special = unit.substr(1);
360 // The unit is not used, but LyX requires a dummy setting
373 * Find a file with basename \p name in path \p path and an extension
376 string find_file(string const & name, string const & path,
377 char const * const * extensions)
379 for (char const * const * what = extensions; *what; ++what) {
380 string const trial = addExtension(name, *what);
381 if (makeAbsPath(trial, path).exists())
388 void begin_inset(ostream & os, string const & name)
390 os << "\n\\begin_inset " << name;
394 void begin_command_inset(ostream & os, string const & name,
395 string const & latexname)
397 begin_inset(os, "CommandInset ");
398 os << name << "\nLatexCommand " << latexname << '\n';
402 void end_inset(ostream & os)
404 os << "\n\\end_inset\n\n";
408 bool skip_braces(Parser & p)
410 if (p.next_token().cat() != catBegin)
413 if (p.next_token().cat() == catEnd) {
422 /// replace LaTeX commands in \p s from the unicodesymbols file with their
424 docstring convert_unicodesymbols(docstring s)
427 for (size_t i = 0; i < s.size();) {
434 docstring parsed = encodings.fromLaTeXCommand(s, rem,
435 Encodings::TEXT_CMD);
438 if (s.empty() || s[0] != '\\')
447 /// try to convert \p s to a valid InsetCommand argument
448 string convert_command_inset_arg(string s)
451 // since we don't know the input encoding we can't use from_utf8
452 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
453 // LyX cannot handle newlines in a latex command
454 return subst(s, "\n", " ");
458 void handle_backslash(ostream & os, string const & s)
460 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
462 os << "\n\\backslash\n";
469 void handle_ert(ostream & os, string const & s, Context & context)
471 // We must have a valid layout before outputting the ERT inset.
472 context.check_layout(os);
473 Context newcontext(true, context.textclass);
474 begin_inset(os, "ERT");
475 os << "\nstatus collapsed\n";
476 newcontext.check_layout(os);
477 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
479 os << "\n\\backslash\n";
480 else if (*it == '\n') {
481 newcontext.new_paragraph(os);
482 newcontext.check_layout(os);
486 newcontext.check_end_layout(os);
491 void handle_comment(ostream & os, string const & s, Context & context)
493 // TODO: Handle this better
494 Context newcontext(true, context.textclass);
495 begin_inset(os, "ERT");
496 os << "\nstatus collapsed\n";
497 newcontext.check_layout(os);
498 handle_backslash(os, s);
499 // make sure that our comment is the last thing on the line
500 newcontext.new_paragraph(os);
501 newcontext.check_layout(os);
502 newcontext.check_end_layout(os);
507 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
509 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
512 if (checkModule(name, command))
513 return findLayoutWithoutModule(textclass, name, command);
518 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
520 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
523 if (checkModule(name, command))
524 return findInsetLayoutWithoutModule(textclass, name, command);
529 void eat_whitespace(Parser &, ostream &, Context &, bool);
533 * Skips whitespace and braces.
534 * This should be called after a command has been parsed that is not put into
535 * ERT, and where LyX adds "{}" if needed.
537 void skip_spaces_braces(Parser & p, bool keepws = false)
539 /* The following four examples produce the same typeset output and
540 should be handled by this function:
548 // Unfortunately we need to skip comments, too.
549 // We can't use eat_whitespace since writing them after the {}
550 // results in different output in some cases.
551 bool const skipped_spaces = p.skip_spaces(true);
552 bool const skipped_braces = skip_braces(p);
553 if (keepws && skipped_spaces && !skipped_braces)
554 // put back the space (it is better handled by check_space)
555 p.unskip_spaces(true);
559 void output_command_layout(ostream & os, Parser & p, bool outer,
560 Context & parent_context,
561 Layout const * newlayout)
563 TeXFont const oldFont = parent_context.font;
564 // save the current font size
565 string const size = oldFont.size;
566 // reset the font size to default, because the font size switches
567 // don't affect section headings and the like
568 parent_context.font.size = Context::normalfont.size;
569 // we only need to write the font change if we have an open layout
570 if (!parent_context.atParagraphStart())
571 output_font_change(os, oldFont, parent_context.font);
572 parent_context.check_end_layout(os);
573 Context context(true, parent_context.textclass, newlayout,
574 parent_context.layout, parent_context.font);
575 if (parent_context.deeper_paragraph) {
576 // We are beginning a nested environment after a
577 // deeper paragraph inside the outer list environment.
578 // Therefore we don't need to output a "begin deeper".
579 context.need_end_deeper = true;
581 context.check_deeper(os);
582 context.check_layout(os);
583 unsigned int optargs = 0;
584 while (optargs < context.layout->optargs) {
585 eat_whitespace(p, os, context, false);
586 if (p.next_token().cat() == catEscape ||
587 p.next_token().character() != '[')
589 p.get_token(); // eat '['
590 begin_inset(os, "Argument\n");
591 os << "status collapsed\n\n";
592 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
594 eat_whitespace(p, os, context, false);
597 unsigned int reqargs = 0;
598 while (reqargs < context.layout->reqargs) {
599 eat_whitespace(p, os, context, false);
600 if (p.next_token().cat() != catBegin)
602 p.get_token(); // eat '{'
603 begin_inset(os, "Argument\n");
604 os << "status collapsed\n\n";
605 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
607 eat_whitespace(p, os, context, false);
610 parse_text(p, os, FLAG_ITEM, outer, context);
611 context.check_end_layout(os);
612 if (parent_context.deeper_paragraph) {
613 // We must suppress the "end deeper" because we
614 // suppressed the "begin deeper" above.
615 context.need_end_deeper = false;
617 context.check_end_deeper(os);
618 // We don't need really a new paragraph, but
619 // we must make sure that the next item gets a \begin_layout.
620 parent_context.new_paragraph(os);
621 // Set the font size to the original value. No need to output it here
622 // (Context::begin_layout() will do that if needed)
623 parent_context.font.size = size;
628 * Output a space if necessary.
629 * This function gets called for every whitespace token.
631 * We have three cases here:
632 * 1. A space must be suppressed. Example: The lyxcode case below
633 * 2. A space may be suppressed. Example: Spaces before "\par"
634 * 3. A space must not be suppressed. Example: A space between two words
636 * We currently handle only 1. and 3 and from 2. only the case of
637 * spaces before newlines as a side effect.
639 * 2. could be used to suppress as many spaces as possible. This has two effects:
640 * - Reimporting LyX generated LaTeX files changes almost no whitespace
641 * - Superflous whitespace from non LyX generated LaTeX files is removed.
642 * The drawback is that the logic inside the function becomes
643 * complicated, and that is the reason why it is not implemented.
645 void check_space(Parser & p, ostream & os, Context & context)
647 Token const next = p.next_token();
648 Token const curr = p.curr_token();
649 // A space before a single newline and vice versa must be ignored
650 // LyX emits a newline before \end{lyxcode}.
651 // This newline must be ignored,
652 // otherwise LyX will add an additional protected space.
653 if (next.cat() == catSpace ||
654 next.cat() == catNewline ||
655 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
658 context.check_layout(os);
664 * Parse all arguments of \p command
666 void parse_arguments(string const & command,
667 vector<ArgumentType> const & template_arguments,
668 Parser & p, ostream & os, bool outer, Context & context)
670 string ert = command;
671 size_t no_arguments = template_arguments.size();
672 for (size_t i = 0; i < no_arguments; ++i) {
673 switch (template_arguments[i]) {
675 // This argument contains regular LaTeX
676 handle_ert(os, ert + '{', context);
677 eat_whitespace(p, os, context, false);
678 parse_text(p, os, FLAG_ITEM, outer, context);
682 // This argument consists only of a single item.
683 // The presence of '{' or not must be preserved.
685 if (p.next_token().cat() == catBegin)
686 ert += '{' + p.verbatim_item() + '}';
688 ert += p.verbatim_item();
691 // This argument may contain special characters
692 ert += '{' + p.verbatim_item() + '}';
695 // true because we must not eat whitespace
696 // if an optional arg follows we must not strip the
697 // brackets from this one
698 if (i < no_arguments - 1 &&
699 template_arguments[i+1] == optional)
700 ert += p.getFullOpt(true);
702 ert += p.getOpt(true);
706 handle_ert(os, ert, context);
711 * Check whether \p command is a known command. If yes,
712 * handle the command with all arguments.
713 * \return true if the command was parsed, false otherwise.
715 bool parse_command(string const & command, Parser & p, ostream & os,
716 bool outer, Context & context)
718 if (known_commands.find(command) != known_commands.end()) {
719 parse_arguments(command, known_commands[command], p, os,
727 /// Parses a minipage or parbox
728 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
729 unsigned inner_flags, bool outer, Context & parent_context,
730 string const & outer_type, string const & special,
731 string const & inner_type)
735 string hor_pos = "c";
736 // We need to set the height to the LaTeX default of 1\\totalheight
737 // for the case when no height argument is given
738 string height_value = "1";
739 string height_unit = "in";
740 string height_special = "totalheight";
742 if (!inner_type.empty() && p.hasOpt()) {
743 position = p.getArg('[', ']');
744 if (position != "t" && position != "c" && position != "b") {
745 cerr << "invalid position " << position << " for "
746 << inner_type << endl;
750 latex_height = p.getArg('[', ']');
751 translate_box_len(latex_height, height_value, height_unit, height_special);
754 inner_pos = p.getArg('[', ']');
755 if (inner_pos != "c" && inner_pos != "t" &&
756 inner_pos != "b" && inner_pos != "s") {
757 cerr << "invalid inner_pos "
758 << inner_pos << " for "
759 << inner_type << endl;
760 inner_pos = position;
768 if (inner_type.empty()) {
770 latex_width = "\\columnwidth";
773 latex_width = p2.getArg('[', ']');
774 string const opt = p2.getArg('[', ']');
777 if (hor_pos != "l" && hor_pos != "c" &&
779 cerr << "invalid hor_pos " << hor_pos
780 << " for " << outer_type << endl;
786 latex_width = p.verbatim_item();
787 translate_len(latex_width, width_value, width_unit);
788 if (inner_type == "shaded") {
789 eat_whitespace(p, os, parent_context, false);
793 // If we already read the inner box we have to push the inner env
794 if (!outer_type.empty() && !inner_type.empty() &&
795 (inner_flags & FLAG_END))
796 active_environments.push_back(inner_type);
797 // LyX can't handle length variables
798 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
799 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
800 // Look whether there is some content after the end of the
801 // inner box, but before the end of the outer box.
802 // If yes, we need to output ERT.
804 if (inner_flags & FLAG_END)
805 p.verbatimEnvironment(inner_type);
809 bool const outer_env(outer_type == "framed" || outer_type == "minipage");
810 if ((outer_env && p.next_token().asInput() != "\\end") ||
811 (!outer_env && p.next_token().cat() != catEnd)) {
812 // something is between the end of the inner box and
813 // the end of the outer box, so we need to use ERT.
820 if (!outer_type.empty()) {
821 if (outer_flags & FLAG_END)
822 ss << "\\begin{" << outer_type << '}';
824 ss << '\\' << outer_type << '{';
825 if (!special.empty())
829 if (!inner_type.empty()) {
830 if (inner_type != "shaded") {
831 if (inner_flags & FLAG_END)
832 ss << "\\begin{" << inner_type << '}';
834 ss << '\\' << inner_type;
836 if (!position.empty())
837 ss << '[' << position << ']';
838 if (!latex_height.empty())
839 ss << '[' << latex_height << ']';
840 if (!inner_pos.empty())
841 ss << '[' << inner_pos << ']';
842 ss << '{' << latex_width << '}';
843 if (!(inner_flags & FLAG_END))
846 if (inner_type == "shaded")
847 ss << "\\begin{shaded}";
848 handle_ert(os, ss.str(), parent_context);
849 if (!inner_type.empty()) {
850 parse_text(p, os, inner_flags, outer, parent_context);
851 if (inner_flags & FLAG_END)
852 handle_ert(os, "\\end{" + inner_type + '}',
855 handle_ert(os, "}", parent_context);
857 if (!outer_type.empty()) {
858 // If we already read the inner box we have to pop
860 if (!inner_type.empty() && (inner_flags & FLAG_END))
861 active_environments.pop_back();
862 parse_text(p, os, outer_flags, outer, parent_context);
863 if (outer_flags & FLAG_END)
864 handle_ert(os, "\\end{" + outer_type + '}',
867 handle_ert(os, "}", parent_context);
870 // LyX does not like empty positions, so we have
871 // to set them to the LaTeX default values here.
872 if (position.empty())
874 if (inner_pos.empty())
875 inner_pos = position;
876 // FIXME: Support makebox
877 bool const use_makebox = false;
878 parent_context.check_layout(os);
879 begin_inset(os, "Box ");
880 if (outer_type == "framed")
882 else if (outer_type == "framebox")
884 else if (outer_type == "shadowbox")
886 else if ((outer_type == "shaded" && inner_type.empty()) ||
887 (outer_type == "minipage" && inner_type == "shaded")) {
889 preamble.registerAutomaticallyLoadedPackage("color");
890 } else if (outer_type == "doublebox")
892 else if (outer_type.empty())
895 os << outer_type << '\n';
896 os << "position \"" << position << "\"\n";
897 os << "hor_pos \"" << hor_pos << "\"\n";
898 os << "has_inner_box " << !inner_type.empty() << "\n";
899 os << "inner_pos \"" << inner_pos << "\"\n";
900 os << "use_parbox " << (inner_type == "parbox") << '\n';
901 os << "use_makebox " << use_makebox << '\n';
902 os << "width \"" << width_value << width_unit << "\"\n";
903 os << "special \"none\"\n";
904 os << "height \"" << height_value << height_unit << "\"\n";
905 os << "height_special \"" << height_special << "\"\n";
906 os << "status open\n\n";
908 // Unfortunately we can't use parse_text_in_inset:
909 // InsetBox::forcePlainLayout() is hard coded and does not
910 // use the inset layout. Apart from that do we call parse_text
911 // up to two times, but need only one check_end_layout.
913 bool const forcePlainLayout =
914 (!inner_type.empty() || use_makebox) &&
915 outer_type != "shaded" && outer_type != "framed";
916 Context context(true, parent_context.textclass);
917 if (forcePlainLayout)
918 context.layout = &context.textclass.plainLayout();
920 context.font = parent_context.font;
922 // If we have no inner box the contents will be read with the outer box
923 if (!inner_type.empty())
924 parse_text(p, os, inner_flags, outer, context);
926 // Ensure that the end of the outer box is parsed correctly:
927 // The opening brace has been eaten by parse_outer_box()
928 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
929 outer_flags &= ~FLAG_ITEM;
930 outer_flags |= FLAG_BRACE_LAST;
933 // Find end of outer box, output contents if inner_type is
934 // empty and output possible comments
935 if (!outer_type.empty()) {
936 // If we already read the inner box we have to pop
938 if (!inner_type.empty() && (inner_flags & FLAG_END))
939 active_environments.pop_back();
940 // This does not output anything but comments if
941 // inner_type is not empty (see use_ert)
942 parse_text(p, os, outer_flags, outer, context);
945 context.check_end_layout(os);
947 #ifdef PRESERVE_LAYOUT
948 // LyX puts a % after the end of the minipage
949 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
951 //handle_comment(os, "%dummy", parent_context);
954 parent_context.new_paragraph(os);
956 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
957 //handle_comment(os, "%dummy", parent_context);
960 // We add a protected space if something real follows
961 if (p.good() && p.next_token().cat() != catComment) {
962 begin_inset(os, "space ~\n");
971 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
972 Context & parent_context, string const & outer_type,
973 string const & special)
975 eat_whitespace(p, os, parent_context, false);
976 if (flags & FLAG_ITEM) {
978 if (p.next_token().cat() == catBegin)
981 cerr << "Warning: Ignoring missing '{' after \\"
982 << outer_type << '.' << endl;
983 eat_whitespace(p, os, parent_context, false);
986 unsigned int inner_flags = 0;
988 if (outer_type == "minipage") {
997 if (outer_type == "shaded") {
998 // These boxes never have an inner box
1000 } else if (p.next_token().asInput() == "\\parbox") {
1001 inner = p.get_token().cs();
1002 inner_flags = FLAG_ITEM;
1003 } else if (p.next_token().asInput() == "\\begin") {
1004 // Is this a minipage?
1007 inner = p.getArg('{', '}');
1009 if (inner == "minipage" || inner == "shaded")
1010 inner_flags = FLAG_END;
1015 if (inner_flags == FLAG_END) {
1016 if (inner != "shaded")
1020 eat_whitespace(p, os, parent_context, false);
1022 parse_box(p, os, flags, FLAG_END, outer, parent_context,
1023 outer_type, special, inner);
1025 if (inner_flags == FLAG_ITEM) {
1027 eat_whitespace(p, os, parent_context, false);
1029 parse_box(p, os, flags, inner_flags, outer, parent_context,
1030 outer_type, special, inner);
1035 void parse_listings(Parser & p, ostream & os, Context & parent_context)
1037 parent_context.check_layout(os);
1038 begin_inset(os, "listings\n");
1039 os << "inline false\n"
1040 << "status collapsed\n";
1041 Context context(true, parent_context.textclass);
1042 context.layout = &parent_context.textclass.plainLayout();
1043 context.check_layout(os);
1044 string const s = p.verbatimEnvironment("lstlisting");
1045 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
1047 os << "\n\\backslash\n";
1048 else if (*it == '\n') {
1049 // avoid adding an empty paragraph at the end
1051 context.new_paragraph(os);
1052 context.check_layout(os);
1057 context.check_end_layout(os);
1062 /// parse an unknown environment
1063 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
1064 unsigned flags, bool outer,
1065 Context & parent_context)
1067 if (name == "tabbing")
1068 // We need to remember that we have to handle '\=' specially
1069 flags |= FLAG_TABBING;
1071 // We need to translate font changes and paragraphs inside the
1072 // environment to ERT if we have a non standard font.
1073 // Otherwise things like
1074 // \large\begin{foo}\huge bar\end{foo}
1076 bool const specialfont =
1077 (parent_context.font != parent_context.normalfont);
1078 bool const new_layout_allowed = parent_context.new_layout_allowed;
1080 parent_context.new_layout_allowed = false;
1081 handle_ert(os, "\\begin{" + name + "}", parent_context);
1082 parse_text_snippet(p, os, flags, outer, parent_context);
1083 handle_ert(os, "\\end{" + name + "}", parent_context);
1085 parent_context.new_layout_allowed = new_layout_allowed;
1089 void parse_environment(Parser & p, ostream & os, bool outer,
1090 string & last_env, bool & title_layout_found,
1091 Context & parent_context)
1093 Layout const * newlayout;
1094 InsetLayout const * newinsetlayout = 0;
1095 string const name = p.getArg('{', '}');
1096 const bool is_starred = suffixIs(name, '*');
1097 string const unstarred_name = rtrim(name, "*");
1098 active_environments.push_back(name);
1100 if (is_math_env(name)) {
1101 parent_context.check_layout(os);
1102 begin_inset(os, "Formula ");
1103 os << "\\begin{" << name << "}";
1104 parse_math(p, os, FLAG_END, MATH_MODE);
1105 os << "\\end{" << name << "}";
1109 else if (name == "tabular" || name == "longtable") {
1110 eat_whitespace(p, os, parent_context, false);
1111 parent_context.check_layout(os);
1112 begin_inset(os, "Tabular ");
1113 handle_tabular(p, os, name == "longtable", parent_context);
1118 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1119 eat_whitespace(p, os, parent_context, false);
1120 parent_context.check_layout(os);
1121 begin_inset(os, "Float " + unstarred_name + "\n");
1122 // store the float type for subfloats
1123 // subfloats only work with figures and tables
1124 if (unstarred_name == "figure")
1125 float_type = unstarred_name;
1126 else if (unstarred_name == "table")
1127 float_type = unstarred_name;
1131 os << "placement " << p.getArg('[', ']') << '\n';
1132 os << "wide " << convert<string>(is_starred)
1133 << "\nsideways false"
1134 << "\nstatus open\n\n";
1135 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1137 // We don't need really a new paragraph, but
1138 // we must make sure that the next item gets a \begin_layout.
1139 parent_context.new_paragraph(os);
1141 // the float is parsed thus delete the type
1145 else if (unstarred_name == "sidewaysfigure"
1146 || unstarred_name == "sidewaystable") {
1147 eat_whitespace(p, os, parent_context, false);
1148 parent_context.check_layout(os);
1149 if (unstarred_name == "sidewaysfigure")
1150 begin_inset(os, "Float figure\n");
1152 begin_inset(os, "Float table\n");
1153 os << "wide " << convert<string>(is_starred)
1154 << "\nsideways true"
1155 << "\nstatus open\n\n";
1156 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1158 // We don't need really a new paragraph, but
1159 // we must make sure that the next item gets a \begin_layout.
1160 parent_context.new_paragraph(os);
1164 else if (name == "wrapfigure" || name == "wraptable") {
1165 // syntax is \begin{wrapfigure}[lines]{placement}[overhang]{width}
1166 eat_whitespace(p, os, parent_context, false);
1167 parent_context.check_layout(os);
1170 string overhang = "0col%";
1173 lines = p.getArg('[', ']');
1174 string const placement = p.getArg('{', '}');
1176 overhang = p.getArg('[', ']');
1177 string const width = p.getArg('{', '}');
1179 if (name == "wrapfigure")
1180 begin_inset(os, "Wrap figure\n");
1182 begin_inset(os, "Wrap table\n");
1183 os << "lines " << lines
1184 << "\nplacement " << placement
1185 << "\noverhang " << lyx::translate_len(overhang)
1186 << "\nwidth " << lyx::translate_len(width)
1187 << "\nstatus open\n\n";
1188 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1190 // We don't need really a new paragraph, but
1191 // we must make sure that the next item gets a \begin_layout.
1192 parent_context.new_paragraph(os);
1196 else if (name == "minipage") {
1197 eat_whitespace(p, os, parent_context, false);
1198 // Test whether this is an outer box of a shaded box
1200 // swallow arguments
1201 while (p.hasOpt()) {
1203 p.skip_spaces(true);
1206 p.skip_spaces(true);
1207 Token t = p.get_token();
1208 bool shaded = false;
1209 if (t.asInput() == "\\begin") {
1210 p.skip_spaces(true);
1211 if (p.getArg('{', '}') == "shaded")
1216 parse_outer_box(p, os, FLAG_END, outer,
1217 parent_context, name, "shaded");
1219 parse_box(p, os, 0, FLAG_END, outer, parent_context,
1224 else if (name == "comment") {
1225 eat_whitespace(p, os, parent_context, false);
1226 parent_context.check_layout(os);
1227 begin_inset(os, "Note Comment\n");
1228 os << "status open\n";
1229 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1232 skip_braces(p); // eat {} that might by set by LyX behind comments
1235 else if (name == "lyxgreyedout") {
1236 eat_whitespace(p, os, parent_context, false);
1237 parent_context.check_layout(os);
1238 begin_inset(os, "Note Greyedout\n");
1239 os << "status open\n";
1240 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1243 if (!preamble.notefontcolor().empty())
1244 preamble.registerAutomaticallyLoadedPackage("color");
1247 else if (name == "framed" || name == "shaded") {
1248 eat_whitespace(p, os, parent_context, false);
1249 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1253 else if (name == "lstlisting") {
1254 eat_whitespace(p, os, parent_context, false);
1255 // FIXME handle listings with parameters
1256 // If this is added, don't forgot to handle the
1257 // automatic color package loading
1259 parse_unknown_environment(p, name, os, FLAG_END,
1260 outer, parent_context);
1262 parse_listings(p, os, parent_context);
1266 else if (!parent_context.new_layout_allowed)
1267 parse_unknown_environment(p, name, os, FLAG_END, outer,
1270 // Alignment and spacing settings
1271 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1272 // therefore are totally broken!
1273 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1274 // they are commands not environments. They are furthermore switches that
1275 // can be ended by another switches, but also by commands like \footnote or
1276 // \parbox. So the only safe way is to leave them untouched.
1277 else if (name == "center" || name == "centering" ||
1278 name == "flushleft" || name == "flushright" ||
1279 name == "singlespace" || name == "onehalfspace" ||
1280 name == "doublespace" || name == "spacing") {
1281 eat_whitespace(p, os, parent_context, false);
1282 // We must begin a new paragraph if not already done
1283 if (! parent_context.atParagraphStart()) {
1284 parent_context.check_end_layout(os);
1285 parent_context.new_paragraph(os);
1287 if (name == "flushleft")
1288 parent_context.add_extra_stuff("\\align left\n");
1289 else if (name == "flushright")
1290 parent_context.add_extra_stuff("\\align right\n");
1291 else if (name == "center" || name == "centering")
1292 parent_context.add_extra_stuff("\\align center\n");
1293 else if (name == "singlespace")
1294 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1295 else if (name == "onehalfspace")
1296 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1297 else if (name == "doublespace")
1298 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1299 else if (name == "spacing")
1300 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1301 parse_text(p, os, FLAG_END, outer, parent_context);
1302 // Just in case the environment is empty
1303 parent_context.extra_stuff.erase();
1304 // We must begin a new paragraph to reset the alignment
1305 parent_context.new_paragraph(os);
1309 // The single '=' is meant here.
1310 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1311 eat_whitespace(p, os, parent_context, false);
1312 Context context(true, parent_context.textclass, newlayout,
1313 parent_context.layout, parent_context.font);
1314 if (parent_context.deeper_paragraph) {
1315 // We are beginning a nested environment after a
1316 // deeper paragraph inside the outer list environment.
1317 // Therefore we don't need to output a "begin deeper".
1318 context.need_end_deeper = true;
1320 parent_context.check_end_layout(os);
1321 if (last_env == name) {
1322 // we need to output a separator since LyX would export
1323 // the two environments as one otherwise (bug 5716)
1324 docstring const sep = from_ascii("--Separator--");
1325 TeX2LyXDocClass const & textclass(parent_context.textclass);
1326 if (textclass.hasLayout(sep)) {
1327 Context newcontext(parent_context);
1328 newcontext.layout = &(textclass[sep]);
1329 newcontext.check_layout(os);
1330 newcontext.check_end_layout(os);
1332 parent_context.check_layout(os);
1333 begin_inset(os, "Note Note\n");
1334 os << "status closed\n";
1335 Context newcontext(true, textclass,
1336 &(textclass.defaultLayout()));
1337 newcontext.check_layout(os);
1338 newcontext.check_end_layout(os);
1340 parent_context.check_end_layout(os);
1343 switch (context.layout->latextype) {
1344 case LATEX_LIST_ENVIRONMENT:
1345 context.add_par_extra_stuff("\\labelwidthstring "
1346 + p.verbatim_item() + '\n');
1349 case LATEX_BIB_ENVIRONMENT:
1350 p.verbatim_item(); // swallow next arg
1356 context.check_deeper(os);
1357 // handle known optional and required arguments
1358 // layouts require all optional arguments before the required ones
1359 // Unfortunately LyX can't handle arguments of list arguments (bug 7468):
1360 // It is impossible to place anything after the environment name,
1361 // but before the first \\item.
1362 if (context.layout->latextype == LATEX_ENVIRONMENT) {
1363 bool need_layout = true;
1364 unsigned int optargs = 0;
1365 while (optargs < context.layout->optargs) {
1366 eat_whitespace(p, os, context, false);
1367 if (p.next_token().cat() == catEscape ||
1368 p.next_token().character() != '[')
1370 p.get_token(); // eat '['
1372 context.check_layout(os);
1373 need_layout = false;
1375 begin_inset(os, "Argument\n");
1376 os << "status collapsed\n\n";
1377 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1379 eat_whitespace(p, os, context, false);
1382 unsigned int reqargs = 0;
1383 while (reqargs < context.layout->reqargs) {
1384 eat_whitespace(p, os, context, false);
1385 if (p.next_token().cat() != catBegin)
1387 p.get_token(); // eat '{'
1389 context.check_layout(os);
1390 need_layout = false;
1392 begin_inset(os, "Argument\n");
1393 os << "status collapsed\n\n";
1394 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
1396 eat_whitespace(p, os, context, false);
1400 parse_text(p, os, FLAG_END, outer, context);
1401 context.check_end_layout(os);
1402 if (parent_context.deeper_paragraph) {
1403 // We must suppress the "end deeper" because we
1404 // suppressed the "begin deeper" above.
1405 context.need_end_deeper = false;
1407 context.check_end_deeper(os);
1408 parent_context.new_paragraph(os);
1410 if (!title_layout_found)
1411 title_layout_found = newlayout->intitle;
1414 // The single '=' is meant here.
1415 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1416 eat_whitespace(p, os, parent_context, false);
1417 parent_context.check_layout(os);
1418 begin_inset(os, "Flex ");
1419 os << to_utf8(newinsetlayout->name()) << '\n'
1420 << "status collapsed\n";
1421 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1425 else if (name == "appendix") {
1426 // This is no good latex style, but it works and is used in some documents...
1427 eat_whitespace(p, os, parent_context, false);
1428 parent_context.check_end_layout(os);
1429 Context context(true, parent_context.textclass, parent_context.layout,
1430 parent_context.layout, parent_context.font);
1431 context.check_layout(os);
1432 os << "\\start_of_appendix\n";
1433 parse_text(p, os, FLAG_END, outer, context);
1434 context.check_end_layout(os);
1438 else if (known_environments.find(name) != known_environments.end()) {
1439 vector<ArgumentType> arguments = known_environments[name];
1440 // The last "argument" denotes wether we may translate the
1441 // environment contents to LyX
1442 // The default required if no argument is given makes us
1443 // compatible with the reLyXre environment.
1444 ArgumentType contents = arguments.empty() ?
1447 if (!arguments.empty())
1448 arguments.pop_back();
1449 // See comment in parse_unknown_environment()
1450 bool const specialfont =
1451 (parent_context.font != parent_context.normalfont);
1452 bool const new_layout_allowed =
1453 parent_context.new_layout_allowed;
1455 parent_context.new_layout_allowed = false;
1456 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1457 outer, parent_context);
1458 if (contents == verbatim)
1459 handle_ert(os, p.verbatimEnvironment(name),
1462 parse_text_snippet(p, os, FLAG_END, outer,
1464 handle_ert(os, "\\end{" + name + "}", parent_context);
1466 parent_context.new_layout_allowed = new_layout_allowed;
1470 parse_unknown_environment(p, name, os, FLAG_END, outer,
1474 active_environments.pop_back();
1478 /// parses a comment and outputs it to \p os.
1479 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1481 LASSERT(t.cat() == catComment, return);
1482 if (!t.cs().empty()) {
1483 context.check_layout(os);
1484 handle_comment(os, '%' + t.cs(), context);
1485 if (p.next_token().cat() == catNewline) {
1486 // A newline after a comment line starts a new
1488 if (context.new_layout_allowed) {
1489 if(!context.atParagraphStart())
1490 // Only start a new paragraph if not already
1491 // done (we might get called recursively)
1492 context.new_paragraph(os);
1494 handle_ert(os, "\n", context);
1495 eat_whitespace(p, os, context, true);
1498 // "%\n" combination
1505 * Reads spaces and comments until the first non-space, non-comment token.
1506 * New paragraphs (double newlines or \\par) are handled like simple spaces
1507 * if \p eatParagraph is true.
1508 * Spaces are skipped, but comments are written to \p os.
1510 void eat_whitespace(Parser & p, ostream & os, Context & context,
1514 Token const & t = p.get_token();
1515 if (t.cat() == catComment)
1516 parse_comment(p, os, t, context);
1517 else if ((! eatParagraph && p.isParagraph()) ||
1518 (t.cat() != catSpace && t.cat() != catNewline)) {
1527 * Set a font attribute, parse text and reset the font attribute.
1528 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1529 * \param currentvalue Current value of the attribute. Is set to the new
1530 * value during parsing.
1531 * \param newvalue New value of the attribute
1533 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1534 Context & context, string const & attribute,
1535 string & currentvalue, string const & newvalue)
1537 context.check_layout(os);
1538 string const oldvalue = currentvalue;
1539 currentvalue = newvalue;
1540 os << '\n' << attribute << ' ' << newvalue << "\n";
1541 parse_text_snippet(p, os, flags, outer, context);
1542 context.check_layout(os);
1543 os << '\n' << attribute << ' ' << oldvalue << "\n";
1544 currentvalue = oldvalue;
1548 /// get the arguments of a natbib or jurabib citation command
1549 void get_cite_arguments(Parser & p, bool natbibOrder,
1550 string & before, string & after)
1552 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1554 // text before the citation
1556 // text after the citation
1557 after = p.getFullOpt();
1559 if (!after.empty()) {
1560 before = p.getFullOpt();
1561 if (natbibOrder && !before.empty())
1562 swap(before, after);
1567 /// Convert filenames with TeX macros and/or quotes to something LyX
1569 string const normalize_filename(string const & name)
1571 Parser p(trim(name, "\""));
1574 Token const & t = p.get_token();
1575 if (t.cat() != catEscape)
1577 else if (t.cs() == "lyxdot") {
1578 // This is used by LyX for simple dots in relative
1582 } else if (t.cs() == "space") {
1592 /// Convert \p name from TeX convention (relative to master file) to LyX
1593 /// convention (relative to .lyx file) if it is relative
1594 void fix_relative_filename(string & name)
1596 if (FileName::isAbsolute(name))
1599 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1600 from_utf8(getParentFilePath())));
1604 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1605 void parse_noweb(Parser & p, ostream & os, Context & context)
1607 // assemble the rest of the keyword
1611 Token const & t = p.get_token();
1612 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1615 scrap = (p.good() && p.next_token().asInput() == "=");
1617 name += p.get_token().asInput();
1620 name += t.asInput();
1623 if (!scrap || !context.new_layout_allowed ||
1624 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1625 cerr << "Warning: Could not interpret '" << name
1626 << "'. Ignoring it." << endl;
1630 // We use new_paragraph instead of check_end_layout because the stuff
1631 // following the noweb chunk needs to start with a \begin_layout.
1632 // This may create a new paragraph even if there was none in the
1633 // noweb file, but the alternative is an invalid LyX file. Since
1634 // noweb code chunks are implemented with a layout style in LyX they
1635 // always must be in an own paragraph.
1636 context.new_paragraph(os);
1637 Context newcontext(true, context.textclass,
1638 &context.textclass[from_ascii("Scrap")]);
1639 newcontext.check_layout(os);
1642 Token const & t = p.get_token();
1643 // We abuse the parser a bit, because this is no TeX syntax
1645 if (t.cat() == catEscape)
1646 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1649 Context tmp(false, context.textclass,
1650 &context.textclass[from_ascii("Scrap")]);
1651 tmp.need_end_layout = true;
1652 tmp.check_layout(oss);
1653 os << subst(t.asInput(), "\n", oss.str());
1655 // The scrap chunk is ended by an @ at the beginning of a line.
1656 // After the @ the line may contain a comment and/or
1657 // whitespace, but nothing else.
1658 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1659 (p.next_token().cat() == catSpace ||
1660 p.next_token().cat() == catNewline ||
1661 p.next_token().cat() == catComment)) {
1662 while (p.good() && p.next_token().cat() == catSpace)
1663 os << p.get_token().asInput();
1664 if (p.next_token().cat() == catComment)
1665 // The comment includes a final '\n'
1666 os << p.get_token().asInput();
1668 if (p.next_token().cat() == catNewline)
1675 newcontext.check_end_layout(os);
1679 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1680 bool is_macro(Parser & p)
1682 Token first = p.curr_token();
1683 if (first.cat() != catEscape || !p.good())
1685 if (first.cs() == "def")
1687 if (first.cs() != "global" && first.cs() != "long")
1689 Token second = p.get_token();
1691 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1692 second.cat() == catNewline || second.cat() == catComment)) {
1693 second = p.get_token();
1696 bool secondvalid = second.cat() == catEscape;
1698 bool thirdvalid = false;
1699 if (p.good() && first.cs() == "global" && secondvalid &&
1700 second.cs() == "long") {
1701 third = p.get_token();
1703 while (p.good() && !p.isParagraph() &&
1704 (third.cat() == catSpace ||
1705 third.cat() == catNewline ||
1706 third.cat() == catComment)) {
1707 third = p.get_token();
1710 thirdvalid = third.cat() == catEscape;
1712 for (int i = 0; i < pos; ++i)
1717 return (first.cs() == "global" || first.cs() == "long") &&
1718 second.cs() == "def";
1719 return first.cs() == "global" && second.cs() == "long" &&
1720 third.cs() == "def";
1724 /// Parse a macro definition (assumes that is_macro() returned true)
1725 void parse_macro(Parser & p, ostream & os, Context & context)
1727 context.check_layout(os);
1728 Token first = p.curr_token();
1731 string command = first.asInput();
1732 if (first.cs() != "def") {
1734 eat_whitespace(p, os, context, false);
1735 second = p.curr_token();
1736 command += second.asInput();
1737 if (second.cs() != "def") {
1739 eat_whitespace(p, os, context, false);
1740 third = p.curr_token();
1741 command += third.asInput();
1744 eat_whitespace(p, os, context, false);
1745 string const name = p.get_token().cs();
1746 eat_whitespace(p, os, context, false);
1752 while (p.next_token().cat() != catBegin) {
1753 if (p.next_token().cat() == catParameter) {
1758 // followed by number?
1759 if (p.next_token().cat() == catOther) {
1760 char c = p.getChar();
1762 // number = current arity + 1?
1763 if (c == arity + '0' + 1)
1768 paramtext += p.get_token().cs();
1770 paramtext += p.get_token().cs();
1775 // only output simple (i.e. compatible) macro as FormulaMacros
1776 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1778 context.check_layout(os);
1779 begin_inset(os, "FormulaMacro");
1780 os << "\n\\def" << ert;
1783 handle_ert(os, command + ert, context);
1786 } // anonymous namespace
1789 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1792 Layout const * newlayout = 0;
1793 InsetLayout const * newinsetlayout = 0;
1794 // Store the latest bibliographystyle and nocite{*} option
1795 // (needed for bibtex inset)
1797 string bibliographystyle;
1798 bool const use_natbib = preamble.isPackageUsed("natbib");
1799 bool const use_jurabib = preamble.isPackageUsed("jurabib");
1801 bool title_layout_found = false;
1803 Token const & t = p.get_token();
1806 debugToken(cerr, t, flags);
1809 if (flags & FLAG_ITEM) {
1810 if (t.cat() == catSpace)
1813 flags &= ~FLAG_ITEM;
1814 if (t.cat() == catBegin) {
1815 // skip the brace and collect everything to the next matching
1817 flags |= FLAG_BRACE_LAST;
1821 // handle only this single token, leave the loop if done
1822 flags |= FLAG_LEAVE;
1825 if (t.cat() != catEscape && t.character() == ']' &&
1826 (flags & FLAG_BRACK_LAST))
1828 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1831 // If there is anything between \end{env} and \begin{env} we
1832 // don't need to output a separator.
1833 if (t.cat() != catSpace && t.cat() != catNewline &&
1834 t.asInput() != "\\begin")
1840 if (t.cat() == catMath) {
1841 // we are inside some text mode thingy, so opening new math is allowed
1842 context.check_layout(os);
1843 begin_inset(os, "Formula ");
1844 Token const & n = p.get_token();
1845 if (n.cat() == catMath && outer) {
1846 // TeX's $$...$$ syntax for displayed math
1848 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1850 p.get_token(); // skip the second '$' token
1852 // simple $...$ stuff
1855 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1861 else if (t.cat() == catSuper || t.cat() == catSub)
1862 cerr << "catcode " << t << " illegal in text mode\n";
1864 // Basic support for english quotes. This should be
1865 // extended to other quotes, but is not so easy (a
1866 // left english quote is the same as a right german
1868 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1869 context.check_layout(os);
1870 begin_inset(os, "Quotes ");
1876 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1877 context.check_layout(os);
1878 begin_inset(os, "Quotes ");
1885 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1886 context.check_layout(os);
1887 begin_inset(os, "Quotes ");
1894 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1895 context.check_layout(os);
1896 begin_inset(os, "Quotes ");
1903 else if (t.asInput() == "<"
1904 && p.next_token().asInput() == "<" && noweb_mode) {
1906 parse_noweb(p, os, context);
1909 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1910 check_space(p, os, context);
1912 else if (t.character() == '[' && noweb_mode &&
1913 p.next_token().character() == '[') {
1914 // These can contain underscores
1916 string const s = p.getFullOpt() + ']';
1917 if (p.next_token().character() == ']')
1920 cerr << "Warning: Inserting missing ']' in '"
1921 << s << "'." << endl;
1922 handle_ert(os, s, context);
1925 else if (t.cat() == catLetter) {
1926 context.check_layout(os);
1927 // Workaround for bug 4752.
1928 // FIXME: This whole code block needs to be removed
1929 // when the bug is fixed and tex2lyx produces
1930 // the updated file format.
1931 // The replacement algorithm in LyX is so stupid that
1932 // it even translates a phrase if it is part of a word.
1933 bool handled = false;
1934 for (int const * l = known_phrase_lengths; *l; ++l) {
1935 string phrase = t.cs();
1936 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1937 phrase += p.get_token().cs();
1938 if (is_known(phrase, known_coded_phrases)) {
1939 handle_ert(os, phrase, context);
1943 for (size_t i = 1; i < phrase.length(); ++i)
1951 else if (t.cat() == catOther ||
1952 t.cat() == catAlign ||
1953 t.cat() == catParameter) {
1954 // This translates "&" to "\\&" which may be wrong...
1955 context.check_layout(os);
1959 else if (p.isParagraph()) {
1960 if (context.new_layout_allowed)
1961 context.new_paragraph(os);
1963 handle_ert(os, "\\par ", context);
1964 eat_whitespace(p, os, context, true);
1967 else if (t.cat() == catActive) {
1968 context.check_layout(os);
1969 if (t.character() == '~') {
1970 if (context.layout->free_spacing)
1973 begin_inset(os, "space ~\n");
1980 else if (t.cat() == catBegin &&
1981 p.next_token().cat() == catEnd) {
1983 Token const prev = p.prev_token();
1985 if (p.next_token().character() == '`' ||
1986 (prev.character() == '-' &&
1987 p.next_token().character() == '-'))
1988 ; // ignore it in {}`` or -{}-
1990 handle_ert(os, "{}", context);
1994 else if (t.cat() == catBegin) {
1995 context.check_layout(os);
1996 // special handling of font attribute changes
1997 Token const prev = p.prev_token();
1998 Token const next = p.next_token();
1999 TeXFont const oldFont = context.font;
2000 if (next.character() == '[' ||
2001 next.character() == ']' ||
2002 next.character() == '*') {
2004 if (p.next_token().cat() == catEnd) {
2009 handle_ert(os, "{", context);
2010 parse_text_snippet(p, os,
2013 handle_ert(os, "}", context);
2015 } else if (! context.new_layout_allowed) {
2016 handle_ert(os, "{", context);
2017 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2019 handle_ert(os, "}", context);
2020 } else if (is_known(next.cs(), known_sizes)) {
2021 // next will change the size, so we must
2023 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2025 if (!context.atParagraphStart())
2027 << context.font.size << "\n";
2028 } else if (is_known(next.cs(), known_font_families)) {
2029 // next will change the font family, so we
2030 // must reset it here
2031 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2033 if (!context.atParagraphStart())
2035 << context.font.family << "\n";
2036 } else if (is_known(next.cs(), known_font_series)) {
2037 // next will change the font series, so we
2038 // must reset it here
2039 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2041 if (!context.atParagraphStart())
2043 << context.font.series << "\n";
2044 } else if (is_known(next.cs(), known_font_shapes)) {
2045 // next will change the font shape, so we
2046 // must reset it here
2047 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2049 if (!context.atParagraphStart())
2051 << context.font.shape << "\n";
2052 } else if (is_known(next.cs(), known_old_font_families) ||
2053 is_known(next.cs(), known_old_font_series) ||
2054 is_known(next.cs(), known_old_font_shapes)) {
2055 // next will change the font family, series
2056 // and shape, so we must reset it here
2057 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2059 if (!context.atParagraphStart())
2061 << context.font.family
2063 << context.font.series
2065 << context.font.shape << "\n";
2067 handle_ert(os, "{", context);
2068 parse_text_snippet(p, os, FLAG_BRACE_LAST,
2070 handle_ert(os, "}", context);
2074 else if (t.cat() == catEnd) {
2075 if (flags & FLAG_BRACE_LAST) {
2078 cerr << "stray '}' in text\n";
2079 handle_ert(os, "}", context);
2082 else if (t.cat() == catComment)
2083 parse_comment(p, os, t, context);
2086 // control sequences
2089 else if (t.cs() == "(") {
2090 context.check_layout(os);
2091 begin_inset(os, "Formula");
2093 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
2098 else if (t.cs() == "[") {
2099 context.check_layout(os);
2100 begin_inset(os, "Formula");
2102 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
2107 else if (t.cs() == "begin")
2108 parse_environment(p, os, outer, last_env,
2109 title_layout_found, context);
2111 else if (t.cs() == "end") {
2112 if (flags & FLAG_END) {
2113 // eat environment name
2114 string const name = p.getArg('{', '}');
2115 if (name != active_environment())
2116 cerr << "\\end{" + name + "} does not match \\begin{"
2117 + active_environment() + "}\n";
2120 p.error("found 'end' unexpectedly");
2123 else if (t.cs() == "item") {
2126 bool optarg = false;
2127 if (p.next_token().cat() != catEscape &&
2128 p.next_token().character() == '[') {
2129 p.get_token(); // eat '['
2130 s = parse_text_snippet(p, FLAG_BRACK_LAST,
2135 context.check_layout(os);
2136 if (context.has_item) {
2137 // An item in an unknown list-like environment
2138 // FIXME: Do this in check_layout()!
2139 context.has_item = false;
2141 handle_ert(os, "\\item", context);
2143 handle_ert(os, "\\item ", context);
2146 if (context.layout->labeltype != LABEL_MANUAL) {
2147 // LyX does not support \item[\mybullet]
2148 // in itemize environments
2149 handle_ert(os, "[", context);
2151 handle_ert(os, "]", context);
2152 } else if (!s.empty()) {
2153 // The space is needed to separate the
2154 // item from the rest of the sentence.
2156 eat_whitespace(p, os, context, false);
2161 else if (t.cs() == "bibitem") {
2163 context.check_layout(os);
2164 string label = convert_command_inset_arg(p.getArg('[', ']'));
2165 string key = convert_command_inset_arg(p.verbatim_item());
2166 if (contains(label, '\\') || contains(key, '\\')) {
2167 // LyX can't handle LaTeX commands in labels or keys
2168 handle_ert(os, t.asInput() + '[' + label +
2169 "]{" + p.verbatim_item() + '}',
2172 begin_command_inset(os, "bibitem", "bibitem");
2173 os << "label \"" << label << "\"\n"
2174 "key \"" << key << "\"\n";
2179 else if (is_macro(p))
2180 parse_macro(p, os, context);
2182 else if (t.cs() == "noindent") {
2184 context.add_par_extra_stuff("\\noindent\n");
2187 else if (t.cs() == "appendix") {
2188 context.add_par_extra_stuff("\\start_of_appendix\n");
2189 // We need to start a new paragraph. Otherwise the
2190 // appendix in 'bla\appendix\chapter{' would start
2192 context.new_paragraph(os);
2193 // We need to make sure that the paragraph is
2194 // generated even if it is empty. Otherwise the
2195 // appendix in '\par\appendix\par\chapter{' would
2197 context.check_layout(os);
2198 // FIXME: This is a hack to prevent paragraph
2199 // deletion if it is empty. Handle this better!
2201 "%dummy comment inserted by tex2lyx to "
2202 "ensure that this paragraph is not empty",
2204 // Both measures above may generate an additional
2205 // empty paragraph, but that does not hurt, because
2206 // whitespace does not matter here.
2207 eat_whitespace(p, os, context, true);
2210 // Must catch empty dates before findLayout is called below
2211 else if (t.cs() == "date") {
2212 string const date = p.verbatim_item();
2214 preamble.suppressDate(true);
2216 preamble.suppressDate(false);
2217 if (context.new_layout_allowed &&
2218 (newlayout = findLayout(context.textclass,
2221 output_command_layout(os, p, outer,
2222 context, newlayout);
2224 if (!title_layout_found)
2225 title_layout_found = newlayout->intitle;
2227 handle_ert(os, "\\date{" + date + '}',
2232 // Starred section headings
2233 // Must attempt to parse "Section*" before "Section".
2234 else if ((p.next_token().asInput() == "*") &&
2235 context.new_layout_allowed &&
2236 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2239 output_command_layout(os, p, outer, context, newlayout);
2241 if (!title_layout_found)
2242 title_layout_found = newlayout->intitle;
2245 // Section headings and the like
2246 else if (context.new_layout_allowed &&
2247 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2249 output_command_layout(os, p, outer, context, newlayout);
2251 if (!title_layout_found)
2252 title_layout_found = newlayout->intitle;
2255 else if (t.cs() == "caption") {
2257 context.check_layout(os);
2259 begin_inset(os, "Caption\n");
2260 Context newcontext(true, context.textclass);
2261 newcontext.font = context.font;
2262 newcontext.check_layout(os);
2263 if (p.next_token().cat() != catEscape &&
2264 p.next_token().character() == '[') {
2265 p.get_token(); // eat '['
2266 begin_inset(os, "Argument\n");
2267 os << "status collapsed\n";
2268 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2270 eat_whitespace(p, os, context, false);
2272 parse_text(p, os, FLAG_ITEM, outer, context);
2273 context.check_end_layout(os);
2274 // We don't need really a new paragraph, but
2275 // we must make sure that the next item gets a \begin_layout.
2276 context.new_paragraph(os);
2279 newcontext.check_end_layout(os);
2282 else if (t.cs() == "subfloat") {
2283 // the syntax is \subfloat[caption]{content}
2284 // if it is a table of figure depends on the surrounding float
2285 bool has_caption = false;
2287 // do nothing if there is no outer float
2288 if (!float_type.empty()) {
2289 context.check_layout(os);
2291 begin_inset(os, "Float " + float_type + "\n");
2293 << "\nsideways false"
2294 << "\nstatus collapsed\n\n";
2297 if (p.next_token().cat() != catEscape &&
2298 p.next_token().character() == '[') {
2299 p.get_token(); // eat '['
2300 caption = parse_text_snippet(p, FLAG_BRACK_LAST, outer, context);
2304 parse_text_in_inset(p, os, FLAG_ITEM, outer, context);
2305 // the caption comes always as the last
2307 // we must make sure that the caption gets a \begin_layout
2308 os << "\n\\begin_layout Plain Layout";
2310 begin_inset(os, "Caption\n");
2311 Context newcontext(true, context.textclass);
2312 newcontext.font = context.font;
2313 newcontext.check_layout(os);
2314 os << caption << "\n";
2315 newcontext.check_end_layout(os);
2316 // We don't need really a new paragraph, but
2317 // we must make sure that the next item gets a \begin_layout.
2318 //newcontext.new_paragraph(os);
2322 // We don't need really a new paragraph, but
2323 // we must make sure that the next item gets a \begin_layout.
2325 context.new_paragraph(os);
2328 context.check_end_layout(os);
2329 // close the layout we opened
2331 os << "\n\\end_layout\n";
2333 // if the float type is not supported or there is no surrounding float
2336 string opt_arg = convert_command_inset_arg(p.getArg('[', ']'));
2337 handle_ert(os, t.asInput() + '[' + opt_arg +
2338 "]{" + p.verbatim_item() + '}', context);
2340 handle_ert(os, t.asInput() + "{" + p.verbatim_item() + '}', context);
2344 else if (t.cs() == "includegraphics") {
2345 bool const clip = p.next_token().asInput() == "*";
2348 string const arg = p.getArg('[', ']');
2349 map<string, string> opts;
2350 vector<string> keys;
2351 split_map(arg, opts, keys);
2353 opts["clip"] = string();
2354 string name = normalize_filename(p.verbatim_item());
2356 string const path = getMasterFilePath();
2357 // We want to preserve relative / absolute filenames,
2358 // therefore path is only used for testing
2359 if (!makeAbsPath(name, path).exists()) {
2360 // The file extension is probably missing.
2361 // Now try to find it out.
2362 string const dvips_name =
2363 find_file(name, path,
2364 known_dvips_graphics_formats);
2365 string const pdftex_name =
2366 find_file(name, path,
2367 known_pdftex_graphics_formats);
2368 if (!dvips_name.empty()) {
2369 if (!pdftex_name.empty()) {
2370 cerr << "This file contains the "
2372 "\"\\includegraphics{"
2374 "However, files\n\""
2375 << dvips_name << "\" and\n\""
2376 << pdftex_name << "\"\n"
2377 "both exist, so I had to make a "
2378 "choice and took the first one.\n"
2379 "Please move the unwanted one "
2380 "someplace else and try again\n"
2381 "if my choice was wrong."
2385 } else if (!pdftex_name.empty()) {
2391 if (makeAbsPath(name, path).exists())
2392 fix_relative_filename(name);
2394 cerr << "Warning: Could not find graphics file '"
2395 << name << "'." << endl;
2397 context.check_layout(os);
2398 begin_inset(os, "Graphics ");
2399 os << "\n\tfilename " << name << '\n';
2400 if (opts.find("width") != opts.end())
2402 << translate_len(opts["width"]) << '\n';
2403 if (opts.find("height") != opts.end())
2405 << translate_len(opts["height"]) << '\n';
2406 if (opts.find("scale") != opts.end()) {
2407 istringstream iss(opts["scale"]);
2411 os << "\tscale " << val << '\n';
2413 if (opts.find("angle") != opts.end()) {
2414 os << "\trotateAngle "
2415 << opts["angle"] << '\n';
2416 vector<string>::const_iterator a =
2417 find(keys.begin(), keys.end(), "angle");
2418 vector<string>::const_iterator s =
2419 find(keys.begin(), keys.end(), "width");
2420 if (s == keys.end())
2421 s = find(keys.begin(), keys.end(), "height");
2422 if (s == keys.end())
2423 s = find(keys.begin(), keys.end(), "scale");
2424 if (s != keys.end() && distance(s, a) > 0)
2425 os << "\tscaleBeforeRotation\n";
2427 if (opts.find("origin") != opts.end()) {
2429 string const opt = opts["origin"];
2430 if (opt.find('l') != string::npos) ss << "left";
2431 if (opt.find('r') != string::npos) ss << "right";
2432 if (opt.find('c') != string::npos) ss << "center";
2433 if (opt.find('t') != string::npos) ss << "Top";
2434 if (opt.find('b') != string::npos) ss << "Bottom";
2435 if (opt.find('B') != string::npos) ss << "Baseline";
2436 if (!ss.str().empty())
2437 os << "\trotateOrigin " << ss.str() << '\n';
2439 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2441 if (opts.find("keepaspectratio") != opts.end())
2442 os << "\tkeepAspectRatio\n";
2443 if (opts.find("clip") != opts.end())
2445 if (opts.find("draft") != opts.end())
2447 if (opts.find("bb") != opts.end())
2448 os << "\tBoundingBox "
2449 << opts["bb"] << '\n';
2450 int numberOfbbOptions = 0;
2451 if (opts.find("bbllx") != opts.end())
2452 numberOfbbOptions++;
2453 if (opts.find("bblly") != opts.end())
2454 numberOfbbOptions++;
2455 if (opts.find("bburx") != opts.end())
2456 numberOfbbOptions++;
2457 if (opts.find("bbury") != opts.end())
2458 numberOfbbOptions++;
2459 if (numberOfbbOptions == 4)
2460 os << "\tBoundingBox "
2461 << opts["bbllx"] << " " << opts["bblly"] << " "
2462 << opts["bburx"] << " " << opts["bbury"] << '\n';
2463 else if (numberOfbbOptions > 0)
2464 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2465 numberOfbbOptions = 0;
2466 if (opts.find("natwidth") != opts.end())
2467 numberOfbbOptions++;
2468 if (opts.find("natheight") != opts.end())
2469 numberOfbbOptions++;
2470 if (numberOfbbOptions == 2)
2471 os << "\tBoundingBox 0bp 0bp "
2472 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2473 else if (numberOfbbOptions > 0)
2474 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2475 ostringstream special;
2476 if (opts.find("hiresbb") != opts.end())
2477 special << "hiresbb,";
2478 if (opts.find("trim") != opts.end())
2480 if (opts.find("viewport") != opts.end())
2481 special << "viewport=" << opts["viewport"] << ',';
2482 if (opts.find("totalheight") != opts.end())
2483 special << "totalheight=" << opts["totalheight"] << ',';
2484 if (opts.find("type") != opts.end())
2485 special << "type=" << opts["type"] << ',';
2486 if (opts.find("ext") != opts.end())
2487 special << "ext=" << opts["ext"] << ',';
2488 if (opts.find("read") != opts.end())
2489 special << "read=" << opts["read"] << ',';
2490 if (opts.find("command") != opts.end())
2491 special << "command=" << opts["command"] << ',';
2492 string s_special = special.str();
2493 if (!s_special.empty()) {
2494 // We had special arguments. Remove the trailing ','.
2495 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2497 // TODO: Handle the unknown settings better.
2498 // Warn about invalid options.
2499 // Check whether some option was given twice.
2503 else if (t.cs() == "footnote" ||
2504 (t.cs() == "thanks" && context.layout->intitle)) {
2506 context.check_layout(os);
2507 begin_inset(os, "Foot\n");
2508 os << "status collapsed\n\n";
2509 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2513 else if (t.cs() == "marginpar") {
2515 context.check_layout(os);
2516 begin_inset(os, "Marginal\n");
2517 os << "status collapsed\n\n";
2518 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2522 else if (t.cs() == "ensuremath") {
2524 context.check_layout(os);
2525 string const s = p.verbatim_item();
2526 //FIXME: this never triggers in UTF8
2527 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2530 handle_ert(os, "\\ensuremath{" + s + "}",
2534 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2535 if (title_layout_found) {
2537 skip_spaces_braces(p);
2539 handle_ert(os, t.asInput(), context);
2542 else if (t.cs() == "tableofcontents") {
2543 context.check_layout(os);
2544 begin_command_inset(os, "toc", "tableofcontents");
2546 skip_spaces_braces(p);
2549 else if (t.cs() == "listoffigures") {
2550 context.check_layout(os);
2551 begin_inset(os, "FloatList figure\n");
2553 skip_spaces_braces(p);
2556 else if (t.cs() == "listoftables") {
2557 context.check_layout(os);
2558 begin_inset(os, "FloatList table\n");
2560 skip_spaces_braces(p);
2563 else if (t.cs() == "listof") {
2564 p.skip_spaces(true);
2565 string const name = p.get_token().cs();
2566 if (context.textclass.floats().typeExist(name)) {
2567 context.check_layout(os);
2568 begin_inset(os, "FloatList ");
2571 p.get_token(); // swallow second arg
2573 handle_ert(os, "\\listof{" + name + "}", context);
2576 else if (t.cs() == "textrm")
2577 parse_text_attributes(p, os, FLAG_ITEM, outer,
2578 context, "\\family",
2579 context.font.family, "roman");
2581 else if (t.cs() == "textsf")
2582 parse_text_attributes(p, os, FLAG_ITEM, outer,
2583 context, "\\family",
2584 context.font.family, "sans");
2586 else if (t.cs() == "texttt")
2587 parse_text_attributes(p, os, FLAG_ITEM, outer,
2588 context, "\\family",
2589 context.font.family, "typewriter");
2591 else if (t.cs() == "textmd")
2592 parse_text_attributes(p, os, FLAG_ITEM, outer,
2593 context, "\\series",
2594 context.font.series, "medium");
2596 else if (t.cs() == "textbf")
2597 parse_text_attributes(p, os, FLAG_ITEM, outer,
2598 context, "\\series",
2599 context.font.series, "bold");
2601 else if (t.cs() == "textup")
2602 parse_text_attributes(p, os, FLAG_ITEM, outer,
2604 context.font.shape, "up");
2606 else if (t.cs() == "textit")
2607 parse_text_attributes(p, os, FLAG_ITEM, outer,
2609 context.font.shape, "italic");
2611 else if (t.cs() == "textsl")
2612 parse_text_attributes(p, os, FLAG_ITEM, outer,
2614 context.font.shape, "slanted");
2616 else if (t.cs() == "textsc")
2617 parse_text_attributes(p, os, FLAG_ITEM, outer,
2619 context.font.shape, "smallcaps");
2621 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2622 context.check_layout(os);
2623 TeXFont oldFont = context.font;
2624 context.font.init();
2625 context.font.size = oldFont.size;
2626 os << "\n\\family " << context.font.family << "\n";
2627 os << "\n\\series " << context.font.series << "\n";
2628 os << "\n\\shape " << context.font.shape << "\n";
2629 if (t.cs() == "textnormal") {
2630 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2631 output_font_change(os, context.font, oldFont);
2632 context.font = oldFont;
2634 eat_whitespace(p, os, context, false);
2637 else if (t.cs() == "textcolor") {
2638 // scheme is \textcolor{color name}{text}
2639 string const color = p.verbatim_item();
2640 // we only support the predefined colors of the color package
2641 if (color == "black" || color == "blue" || color == "cyan"
2642 || color == "green" || color == "magenta" || color == "red"
2643 || color == "white" || color == "yellow") {
2644 context.check_layout(os);
2645 os << "\n\\color " << color << "\n";
2646 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2647 context.check_layout(os);
2648 os << "\n\\color inherit\n";
2649 preamble.registerAutomaticallyLoadedPackage("color");
2651 // for custom defined colors
2652 handle_ert(os, t.asInput() + "{" + color + "}", context);
2655 else if (t.cs() == "underbar" || t.cs() == "uline") {
2656 // \underbar is not 100% correct (LyX outputs \uline
2657 // of ulem.sty). The difference is that \ulem allows
2658 // line breaks, and \underbar does not.
2659 // Do NOT handle \underline.
2660 // \underbar cuts through y, g, q, p etc.,
2661 // \underline does not.
2662 context.check_layout(os);
2663 os << "\n\\bar under\n";
2664 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2665 context.check_layout(os);
2666 os << "\n\\bar default\n";
2667 preamble.registerAutomaticallyLoadedPackage("ulem");
2670 else if (t.cs() == "sout") {
2671 context.check_layout(os);
2672 os << "\n\\strikeout on\n";
2673 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2674 context.check_layout(os);
2675 os << "\n\\strikeout default\n";
2676 preamble.registerAutomaticallyLoadedPackage("ulem");
2679 else if (t.cs() == "uuline" || t.cs() == "uwave" ||
2680 t.cs() == "emph" || t.cs() == "noun") {
2681 context.check_layout(os);
2682 os << "\n\\" << t.cs() << " on\n";
2683 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2684 context.check_layout(os);
2685 os << "\n\\" << t.cs() << " default\n";
2686 if (t.cs() == "uuline" || t.cs() == "uwave")
2687 preamble.registerAutomaticallyLoadedPackage("ulem");
2690 else if (t.cs() == "phantom" || t.cs() == "hphantom" ||
2691 t.cs() == "vphantom") {
2692 context.check_layout(os);
2693 if (t.cs() == "phantom")
2694 begin_inset(os, "Phantom Phantom\n");
2695 if (t.cs() == "hphantom")
2696 begin_inset(os, "Phantom HPhantom\n");
2697 if (t.cs() == "vphantom")
2698 begin_inset(os, "Phantom VPhantom\n");
2699 os << "status open\n";
2700 parse_text_in_inset(p, os, FLAG_ITEM, outer, context,
2705 else if (t.cs() == "href") {
2706 context.check_layout(os);
2707 string target = p.getArg('{', '}');
2708 string name = p.getArg('{', '}');
2710 size_t i = target.find(':');
2711 if (i != string::npos) {
2712 type = target.substr(0, i + 1);
2713 if (type == "mailto:" || type == "file:")
2714 target = target.substr(i + 1);
2715 // handle the case that name is equal to target, except of "http://"
2716 else if (target.substr(i + 3) == name && type == "http:")
2719 begin_command_inset(os, "href", "href");
2721 os << "name \"" << name << "\"\n";
2722 os << "target \"" << target << "\"\n";
2723 if (type == "mailto:" || type == "file:")
2724 os << "type \"" << type << "\"\n";
2726 skip_spaces_braces(p);
2729 else if (t.cs() == "lyxline") {
2730 // swallow size argument (it is not used anyway)
2732 if (!context.atParagraphStart()) {
2733 // so our line is in the middle of a paragraph
2734 // we need to add a new line, lest this line
2735 // follow the other content on that line and
2736 // run off the side of the page
2737 // FIXME: This may create an empty paragraph,
2738 // but without that it would not be
2739 // possible to set noindent below.
2740 // Fortunately LaTeX does not care
2741 // about the empty paragraph.
2742 context.new_paragraph(os);
2744 if (preamble.indentParagraphs()) {
2745 // we need to unindent, lest the line be too long
2746 context.add_par_extra_stuff("\\noindent\n");
2748 context.check_layout(os);
2749 begin_command_inset(os, "line", "rule");
2750 os << "offset \"0.5ex\"\n"
2751 "width \"100line%\"\n"
2756 else if (t.cs() == "rule") {
2757 string const offset = (p.hasOpt() ? p.getArg('[', ']') : string());
2758 string const width = p.getArg('{', '}');
2759 string const thickness = p.getArg('{', '}');
2760 context.check_layout(os);
2761 begin_command_inset(os, "line", "rule");
2762 if (!offset.empty())
2763 os << "offset \"" << translate_len(offset) << "\"\n";
2764 os << "width \"" << translate_len(width) << "\"\n"
2765 "height \"" << translate_len(thickness) << "\"\n";
2769 else if (is_known(t.cs(), known_phrases) ||
2770 (t.cs() == "protect" &&
2771 p.next_token().cat() == catEscape &&
2772 is_known(p.next_token().cs(), known_phrases))) {
2773 // LyX sometimes puts a \protect in front, so we have to ignore it
2774 // FIXME: This needs to be changed when bug 4752 is fixed.
2775 char const * const * where = is_known(
2776 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2778 context.check_layout(os);
2779 os << known_coded_phrases[where - known_phrases];
2780 skip_spaces_braces(p);
2783 else if (is_known(t.cs(), known_ref_commands)) {
2784 string const opt = p.getOpt();
2786 context.check_layout(os);
2787 char const * const * where = is_known(t.cs(),
2788 known_ref_commands);
2789 begin_command_inset(os, "ref",
2790 known_coded_ref_commands[where - known_ref_commands]);
2791 os << "reference \""
2792 << convert_command_inset_arg(p.verbatim_item())
2796 // LyX does not support optional arguments of ref commands
2797 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2798 p.verbatim_item() + "}", context);
2802 else if (use_natbib &&
2803 is_known(t.cs(), known_natbib_commands) &&
2804 ((t.cs() != "citefullauthor" &&
2805 t.cs() != "citeyear" &&
2806 t.cs() != "citeyearpar") ||
2807 p.next_token().asInput() != "*")) {
2808 context.check_layout(os);
2809 string command = t.cs();
2810 if (p.next_token().asInput() == "*") {
2814 if (command == "citefullauthor")
2815 // alternative name for "\\citeauthor*"
2816 command = "citeauthor*";
2818 // text before the citation
2820 // text after the citation
2822 get_cite_arguments(p, true, before, after);
2824 if (command == "cite") {
2825 // \cite without optional argument means
2826 // \citet, \cite with at least one optional
2827 // argument means \citep.
2828 if (before.empty() && after.empty())
2833 if (before.empty() && after == "[]")
2834 // avoid \citet[]{a}
2836 else if (before == "[]" && after == "[]") {
2837 // avoid \citet[][]{a}
2841 // remove the brackets around after and before
2842 if (!after.empty()) {
2844 after.erase(after.length() - 1, 1);
2845 after = convert_command_inset_arg(after);
2847 if (!before.empty()) {
2849 before.erase(before.length() - 1, 1);
2850 before = convert_command_inset_arg(before);
2852 begin_command_inset(os, "citation", command);
2853 os << "after " << '"' << after << '"' << "\n";
2854 os << "before " << '"' << before << '"' << "\n";
2856 << convert_command_inset_arg(p.verbatim_item())
2861 else if (use_jurabib &&
2862 is_known(t.cs(), known_jurabib_commands) &&
2863 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2864 context.check_layout(os);
2865 string command = t.cs();
2866 if (p.next_token().asInput() == "*") {
2870 char argumentOrder = '\0';
2871 vector<string> const options =
2872 preamble.getPackageOptions("jurabib");
2873 if (find(options.begin(), options.end(),
2874 "natbiborder") != options.end())
2875 argumentOrder = 'n';
2876 else if (find(options.begin(), options.end(),
2877 "jurabiborder") != options.end())
2878 argumentOrder = 'j';
2880 // text before the citation
2882 // text after the citation
2884 get_cite_arguments(p, argumentOrder != 'j', before, after);
2886 string const citation = p.verbatim_item();
2887 if (!before.empty() && argumentOrder == '\0') {
2888 cerr << "Warning: Assuming argument order "
2889 "of jurabib version 0.6 for\n'"
2890 << command << before << after << '{'
2891 << citation << "}'.\n"
2892 "Add 'jurabiborder' to the jurabib "
2893 "package options if you used an\n"
2894 "earlier jurabib version." << endl;
2896 if (!after.empty()) {
2898 after.erase(after.length() - 1, 1);
2900 if (!before.empty()) {
2902 before.erase(before.length() - 1, 1);
2904 begin_command_inset(os, "citation", command);
2905 os << "after " << '"' << after << '"' << "\n";
2906 os << "before " << '"' << before << '"' << "\n";
2907 os << "key " << '"' << citation << '"' << "\n";
2911 else if (t.cs() == "cite"
2912 || t.cs() == "nocite") {
2913 context.check_layout(os);
2914 string after = convert_command_inset_arg(p.getArg('[', ']'));
2915 string key = convert_command_inset_arg(p.verbatim_item());
2916 // store the case that it is "\nocite{*}" to use it later for
2919 begin_command_inset(os, "citation", t.cs());
2920 os << "after " << '"' << after << '"' << "\n";
2921 os << "key " << '"' << key << '"' << "\n";
2923 } else if (t.cs() == "nocite")
2927 else if (t.cs() == "index") {
2928 context.check_layout(os);
2929 begin_inset(os, "Index idx\n");
2930 os << "status collapsed\n";
2931 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2935 else if (t.cs() == "nomenclature") {
2936 context.check_layout(os);
2937 begin_command_inset(os, "nomenclature", "nomenclature");
2938 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2939 if (!prefix.empty())
2940 os << "prefix " << '"' << prefix << '"' << "\n";
2941 os << "symbol " << '"'
2942 << convert_command_inset_arg(p.verbatim_item());
2943 os << "\"\ndescription \""
2944 << convert_command_inset_arg(p.verbatim_item())
2949 else if (t.cs() == "label") {
2950 context.check_layout(os);
2951 begin_command_inset(os, "label", "label");
2953 << convert_command_inset_arg(p.verbatim_item())
2958 else if (t.cs() == "printindex") {
2959 context.check_layout(os);
2960 begin_command_inset(os, "index_print", "printindex");
2961 os << "type \"idx\"\n";
2963 skip_spaces_braces(p);
2966 else if (t.cs() == "printnomenclature") {
2968 string width_type = "";
2969 context.check_layout(os);
2970 begin_command_inset(os, "nomencl_print", "printnomenclature");
2971 // case of a custom width
2973 width = p.getArg('[', ']');
2974 width = translate_len(width);
2975 width_type = "custom";
2977 // case of no custom width
2978 // the case of no custom width but the width set
2979 // via \settowidth{\nomlabelwidth}{***} cannot be supported
2980 // because the user could have set anything, not only the width
2981 // of the longest label (which would be width_type = "auto")
2982 string label = convert_command_inset_arg(p.getArg('{', '}'));
2983 if (label.empty() && width_type.empty())
2984 width_type = "none";
2985 os << "set_width \"" << width_type << "\"\n";
2986 if (width_type == "custom")
2987 os << "width \"" << width << '\"';
2989 skip_spaces_braces(p);
2992 else if ((t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2993 context.check_layout(os);
2994 begin_inset(os, "script ");
2995 os << t.cs().substr(4) << '\n';
2996 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2998 if (t.cs() == "textsubscript")
2999 preamble.registerAutomaticallyLoadedPackage("subscript");
3002 else if (is_known(t.cs(), known_quotes)) {
3003 char const * const * where = is_known(t.cs(), known_quotes);
3004 context.check_layout(os);
3005 begin_inset(os, "Quotes ");
3006 os << known_coded_quotes[where - known_quotes];
3008 // LyX adds {} after the quote, so we have to eat
3009 // spaces here if there are any before a possible
3011 eat_whitespace(p, os, context, false);
3015 else if (is_known(t.cs(), known_sizes) &&
3016 context.new_layout_allowed) {
3017 char const * const * where = is_known(t.cs(), known_sizes);
3018 context.check_layout(os);
3019 TeXFont const oldFont = context.font;
3020 context.font.size = known_coded_sizes[where - known_sizes];
3021 output_font_change(os, oldFont, context.font);
3022 eat_whitespace(p, os, context, false);
3025 else if (is_known(t.cs(), known_font_families) &&
3026 context.new_layout_allowed) {
3027 char const * const * where =
3028 is_known(t.cs(), known_font_families);
3029 context.check_layout(os);
3030 TeXFont const oldFont = context.font;
3031 context.font.family =
3032 known_coded_font_families[where - known_font_families];
3033 output_font_change(os, oldFont, context.font);
3034 eat_whitespace(p, os, context, false);
3037 else if (is_known(t.cs(), known_font_series) &&
3038 context.new_layout_allowed) {
3039 char const * const * where =
3040 is_known(t.cs(), known_font_series);
3041 context.check_layout(os);
3042 TeXFont const oldFont = context.font;
3043 context.font.series =
3044 known_coded_font_series[where - known_font_series];
3045 output_font_change(os, oldFont, context.font);
3046 eat_whitespace(p, os, context, false);
3049 else if (is_known(t.cs(), known_font_shapes) &&
3050 context.new_layout_allowed) {
3051 char const * const * where =
3052 is_known(t.cs(), known_font_shapes);
3053 context.check_layout(os);
3054 TeXFont const oldFont = context.font;
3055 context.font.shape =
3056 known_coded_font_shapes[where - known_font_shapes];
3057 output_font_change(os, oldFont, context.font);
3058 eat_whitespace(p, os, context, false);
3060 else if (is_known(t.cs(), known_old_font_families) &&
3061 context.new_layout_allowed) {
3062 char const * const * where =
3063 is_known(t.cs(), known_old_font_families);
3064 context.check_layout(os);
3065 TeXFont const oldFont = context.font;
3066 context.font.init();
3067 context.font.size = oldFont.size;
3068 context.font.family =
3069 known_coded_font_families[where - known_old_font_families];
3070 output_font_change(os, oldFont, context.font);
3071 eat_whitespace(p, os, context, false);
3074 else if (is_known(t.cs(), known_old_font_series) &&
3075 context.new_layout_allowed) {
3076 char const * const * where =
3077 is_known(t.cs(), known_old_font_series);
3078 context.check_layout(os);
3079 TeXFont const oldFont = context.font;
3080 context.font.init();
3081 context.font.size = oldFont.size;
3082 context.font.series =
3083 known_coded_font_series[where - known_old_font_series];
3084 output_font_change(os, oldFont, context.font);
3085 eat_whitespace(p, os, context, false);
3088 else if (is_known(t.cs(), known_old_font_shapes) &&
3089 context.new_layout_allowed) {
3090 char const * const * where =
3091 is_known(t.cs(), known_old_font_shapes);
3092 context.check_layout(os);
3093 TeXFont const oldFont = context.font;
3094 context.font.init();
3095 context.font.size = oldFont.size;
3096 context.font.shape =
3097 known_coded_font_shapes[where - known_old_font_shapes];
3098 output_font_change(os, oldFont, context.font);
3099 eat_whitespace(p, os, context, false);
3102 else if (t.cs() == "selectlanguage") {
3103 context.check_layout(os);
3104 // save the language for the case that a
3105 // \foreignlanguage is used
3107 context.font.language = babel2lyx(p.verbatim_item());
3108 os << "\n\\lang " << context.font.language << "\n";
3111 else if (t.cs() == "foreignlanguage") {
3112 string const lang = babel2lyx(p.verbatim_item());
3113 parse_text_attributes(p, os, FLAG_ITEM, outer,
3115 context.font.language, lang);
3118 else if (t.cs() == "inputencoding") {
3119 // nothing to write here
3120 string const enc = subst(p.verbatim_item(), "\n", " ");
3124 else if (t.cs() == "ldots") {
3125 context.check_layout(os);
3126 os << "\\SpecialChar \\ldots{}\n";
3127 skip_spaces_braces(p);
3130 else if (t.cs() == "lyxarrow") {
3131 context.check_layout(os);
3132 os << "\\SpecialChar \\menuseparator\n";
3133 skip_spaces_braces(p);
3136 else if (t.cs() == "textcompwordmark") {
3137 context.check_layout(os);
3138 os << "\\SpecialChar \\textcompwordmark{}\n";
3139 skip_spaces_braces(p);
3142 else if (t.cs() == "slash") {
3143 context.check_layout(os);
3144 os << "\\SpecialChar \\slash{}\n";
3145 skip_spaces_braces(p);
3148 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
3149 context.check_layout(os);
3150 os << "\\SpecialChar \\nobreakdash-\n";
3154 else if (t.cs() == "textquotedbl") {
3155 context.check_layout(os);
3160 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
3161 context.check_layout(os);
3162 os << "\\SpecialChar \\@.\n";
3166 else if (t.cs() == "-") {
3167 context.check_layout(os);
3168 os << "\\SpecialChar \\-\n";
3171 else if (t.cs() == "textasciitilde") {
3172 context.check_layout(os);
3174 skip_spaces_braces(p);
3177 else if (t.cs() == "textasciicircum") {
3178 context.check_layout(os);
3180 skip_spaces_braces(p);
3183 else if (t.cs() == "textbackslash") {
3184 context.check_layout(os);
3185 os << "\n\\backslash\n";
3186 skip_spaces_braces(p);
3189 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
3190 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
3192 context.check_layout(os);
3196 else if (t.cs() == "char") {
3197 context.check_layout(os);
3198 if (p.next_token().character() == '`') {
3200 if (p.next_token().cs() == "\"") {
3205 handle_ert(os, "\\char`", context);
3208 handle_ert(os, "\\char", context);
3212 else if (t.cs() == "verb") {
3213 context.check_layout(os);
3214 char const delimiter = p.next_token().character();
3215 string const arg = p.getArg(delimiter, delimiter);
3217 oss << "\\verb" << delimiter << arg << delimiter;
3218 handle_ert(os, oss.str(), context);
3221 // Problem: \= creates a tabstop inside the tabbing environment
3222 // and else an accent. In the latter case we really would want
3223 // \={o} instead of \= o.
3224 else if (t.cs() == "=" && (flags & FLAG_TABBING))
3225 handle_ert(os, t.asInput(), context);
3227 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
3228 else if (t.cs().size() == 1
3229 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
3230 context.check_layout(os);
3231 // try to see whether the string is in unicodesymbols
3233 string command = t.asInput() + "{"
3234 + trimSpaceAndEol(p.verbatim_item())
3236 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
3239 cerr << "When parsing " << command
3240 << ", result is " << to_utf8(s)
3241 << "+" << to_utf8(rem) << endl;
3244 // we did not find a non-ert version
3245 handle_ert(os, command, context);
3248 else if (t.cs() == "\\") {
3249 context.check_layout(os);
3251 handle_ert(os, "\\\\" + p.getOpt(), context);
3252 else if (p.next_token().asInput() == "*") {
3254 // getOpt() eats the following space if there
3255 // is no optional argument, but that is OK
3256 // here since it has no effect in the output.
3257 handle_ert(os, "\\\\*" + p.getOpt(), context);
3260 begin_inset(os, "Newline newline");
3265 else if (t.cs() == "newline" ||
3266 (t.cs() == "linebreak" && !p.hasOpt())) {
3267 context.check_layout(os);
3268 begin_inset(os, "Newline ");
3271 skip_spaces_braces(p);
3274 else if (t.cs() == "input" || t.cs() == "include"
3275 || t.cs() == "verbatiminput") {
3276 string name = t.cs();
3277 if (t.cs() == "verbatiminput"
3278 && p.next_token().asInput() == "*")
3279 name += p.get_token().asInput();
3280 context.check_layout(os);
3281 string filename(normalize_filename(p.getArg('{', '}')));
3282 string const path = getMasterFilePath();
3283 // We want to preserve relative / absolute filenames,
3284 // therefore path is only used for testing
3285 if ((t.cs() == "include" || t.cs() == "input") &&
3286 !makeAbsPath(filename, path).exists()) {
3287 // The file extension is probably missing.
3288 // Now try to find it out.
3289 string const tex_name =
3290 find_file(filename, path,
3291 known_tex_extensions);
3292 if (!tex_name.empty())
3293 filename = tex_name;
3295 bool external = false;
3297 if (makeAbsPath(filename, path).exists()) {
3298 string const abstexname =
3299 makeAbsPath(filename, path).absFileName();
3300 string const abslyxname =
3301 changeExtension(abstexname, ".lyx");
3302 string const absfigname =
3303 changeExtension(abstexname, ".fig");
3304 fix_relative_filename(filename);
3305 string const lyxname =
3306 changeExtension(filename, ".lyx");
3308 external = FileName(absfigname).exists();
3309 if (t.cs() == "input") {
3310 string const ext = getExtension(abstexname);
3312 // Combined PS/LaTeX:
3313 // x.eps, x.pstex_t (old xfig)
3314 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
3315 FileName const absepsname(
3316 changeExtension(abstexname, ".eps"));
3317 FileName const abspstexname(
3318 changeExtension(abstexname, ".pstex"));
3319 bool const xfigeps =
3320 (absepsname.exists() ||
3321 abspstexname.exists()) &&
3324 // Combined PDF/LaTeX:
3325 // x.pdf, x.pdftex_t (old xfig)
3326 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
3327 FileName const abspdfname(
3328 changeExtension(abstexname, ".pdf"));
3329 bool const xfigpdf =
3330 abspdfname.exists() &&
3331 (ext == "pdftex_t" || ext == "pdf_t");
3335 // Combined PS/PDF/LaTeX:
3336 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
3337 string const absbase2(
3338 removeExtension(abstexname) + "_pspdftex");
3339 FileName const abseps2name(
3340 addExtension(absbase2, ".eps"));
3341 FileName const abspdf2name(
3342 addExtension(absbase2, ".pdf"));
3343 bool const xfigboth =
3344 abspdf2name.exists() &&
3345 abseps2name.exists() && ext == "pspdftex";
3347 xfig = xfigpdf || xfigeps || xfigboth;
3348 external = external && xfig;
3351 outname = changeExtension(filename, ".fig");
3353 // Don't try to convert, the result
3354 // would be full of ERT.
3356 } else if (t.cs() != "verbatiminput" &&
3357 tex2lyx(abstexname, FileName(abslyxname),
3364 cerr << "Warning: Could not find included file '"
3365 << filename << "'." << endl;
3369 begin_inset(os, "External\n");
3370 os << "\ttemplate XFig\n"
3371 << "\tfilename " << outname << '\n';
3373 begin_command_inset(os, "include", name);
3374 os << "preview false\n"
3375 "filename \"" << outname << "\"\n";
3380 else if (t.cs() == "bibliographystyle") {
3381 // store new bibliographystyle
3382 bibliographystyle = p.verbatim_item();
3383 // If any other command than \bibliography and
3384 // \nocite{*} follows, we need to output the style
3385 // (because it might be used by that command).
3386 // Otherwise, it will automatically be output by LyX.
3389 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
3390 if (t2.cat() == catBegin)
3392 if (t2.cat() != catEscape)
3394 if (t2.cs() == "nocite") {
3395 if (p.getArg('{', '}') == "*")
3397 } else if (t2.cs() == "bibliography")
3404 "\\bibliographystyle{" + bibliographystyle + '}',
3409 else if (t.cs() == "bibliography") {
3410 context.check_layout(os);
3411 begin_command_inset(os, "bibtex", "bibtex");
3412 if (!btprint.empty()) {
3413 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3414 // clear the string because the next BibTeX inset can be without the
3415 // \nocite{*} option
3418 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3419 // Do we have a bibliographystyle set?
3420 if (!bibliographystyle.empty())
3421 os << "options " << '"' << bibliographystyle << '"' << "\n";
3425 else if (t.cs() == "parbox")
3426 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3428 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3429 t.cs() == "shadowbox" || t.cs() == "doublebox")
3430 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3432 else if (t.cs() == "framebox") {
3433 string special = p.getFullOpt();
3434 special += p.getOpt();
3435 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3438 //\makebox() is part of the picture environment and different from \makebox{}
3439 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3440 else if (t.cs() == "makebox") {
3441 string arg = t.asInput();
3442 if (p.next_token().character() == '(')
3443 //the syntax is: \makebox(x,y)[position]{content}
3444 arg += p.getFullParentheseArg();
3446 //the syntax is: \makebox[width][position]{content}
3447 arg += p.getFullOpt();
3448 handle_ert(os, arg + p.getFullOpt(), context);
3451 else if (t.cs() == "smallskip" ||
3452 t.cs() == "medskip" ||
3453 t.cs() == "bigskip" ||
3454 t.cs() == "vfill") {
3455 context.check_layout(os);
3456 begin_inset(os, "VSpace ");
3459 skip_spaces_braces(p);
3462 else if (is_known(t.cs(), known_spaces)) {
3463 char const * const * where = is_known(t.cs(), known_spaces);
3464 context.check_layout(os);
3465 begin_inset(os, "space ");
3466 os << '\\' << known_coded_spaces[where - known_spaces]
3469 // LaTeX swallows whitespace after all spaces except
3470 // "\\,". We have to do that here, too, because LyX
3471 // adds "{}" which would make the spaces significant.
3473 eat_whitespace(p, os, context, false);
3474 // LyX adds "{}" after all spaces except "\\ " and
3475 // "\\,", so we have to remove "{}".
3476 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3477 // remove the braces after "\\,", too.
3482 else if (t.cs() == "newpage" ||
3483 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3484 t.cs() == "clearpage" ||
3485 t.cs() == "cleardoublepage") {
3486 context.check_layout(os);
3487 begin_inset(os, "Newpage ");
3490 skip_spaces_braces(p);
3493 else if (t.cs() == "DeclareRobustCommand" ||
3494 t.cs() == "DeclareRobustCommandx" ||
3495 t.cs() == "newcommand" ||
3496 t.cs() == "newcommandx" ||
3497 t.cs() == "providecommand" ||
3498 t.cs() == "providecommandx" ||
3499 t.cs() == "renewcommand" ||
3500 t.cs() == "renewcommandx") {
3501 // DeclareRobustCommand, DeclareRobustCommandx,
3502 // providecommand and providecommandx could be handled
3503 // by parse_command(), but we need to call
3504 // add_known_command() here.
3505 string name = t.asInput();
3506 if (p.next_token().asInput() == "*") {
3507 // Starred form. Eat '*'
3511 string const command = p.verbatim_item();
3512 string const opt1 = p.getFullOpt();
3513 string const opt2 = p.getFullOpt();
3514 add_known_command(command, opt1, !opt2.empty());
3515 string const ert = name + '{' + command + '}' +
3517 '{' + p.verbatim_item() + '}';
3519 if (t.cs() == "DeclareRobustCommand" ||
3520 t.cs() == "DeclareRobustCommandx" ||
3521 t.cs() == "providecommand" ||
3522 t.cs() == "providecommandx" ||
3523 name[name.length()-1] == '*')
3524 handle_ert(os, ert, context);
3526 context.check_layout(os);
3527 begin_inset(os, "FormulaMacro");
3533 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3534 // let could be handled by parse_command(),
3535 // but we need to call add_known_command() here.
3536 string ert = t.asInput();
3539 if (p.next_token().cat() == catBegin) {
3540 name = p.verbatim_item();
3541 ert += '{' + name + '}';
3543 name = p.verbatim_item();
3548 if (p.next_token().cat() == catBegin) {
3549 command = p.verbatim_item();
3550 ert += '{' + command + '}';
3552 command = p.verbatim_item();
3555 // If command is known, make name known too, to parse
3556 // its arguments correctly. For this reason we also
3557 // have commands in syntax.default that are hardcoded.
3558 CommandMap::iterator it = known_commands.find(command);
3559 if (it != known_commands.end())
3560 known_commands[t.asInput()] = it->second;
3561 handle_ert(os, ert, context);
3564 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3565 bool starred = false;
3566 if (p.next_token().asInput() == "*") {
3570 string name = t.asInput();
3571 string const length = p.verbatim_item();
3574 bool valid = splitLatexLength(length, valstring, unit);
3575 bool known_hspace = false;
3576 bool known_vspace = false;
3577 bool known_unit = false;
3580 istringstream iss(valstring);
3583 if (t.cs()[0] == 'h') {
3584 if (unit == "\\fill") {
3589 known_hspace = true;
3592 if (unit == "\\smallskipamount") {
3594 known_vspace = true;
3595 } else if (unit == "\\medskipamount") {
3597 known_vspace = true;
3598 } else if (unit == "\\bigskipamount") {
3600 known_vspace = true;
3601 } else if (unit == "\\fill") {
3603 known_vspace = true;
3607 if (!known_hspace && !known_vspace) {
3608 switch (unitFromString(unit)) {
3629 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3630 // Literal horizontal length or known variable
3631 context.check_layout(os);
3632 begin_inset(os, "space ");
3640 if (known_unit && !known_hspace)
3642 << translate_len(length);
3644 } else if (known_unit || known_vspace) {
3645 // Literal vertical length or known variable
3646 context.check_layout(os);
3647 begin_inset(os, "VSpace ");
3655 // LyX can't handle other length variables in Inset VSpace/space
3660 handle_ert(os, name + '{' + unit + '}', context);
3661 else if (value == -1.0)
3662 handle_ert(os, name + "{-" + unit + '}', context);
3664 handle_ert(os, name + '{' + valstring + unit + '}', context);
3666 handle_ert(os, name + '{' + length + '}', context);
3670 // The single '=' is meant here.
3671 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3673 context.check_layout(os);
3674 begin_inset(os, "Flex ");
3675 os << to_utf8(newinsetlayout->name()) << '\n'
3676 << "status collapsed\n";
3677 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3682 // try to see whether the string is in unicodesymbols
3683 // Only use text mode commands, since we are in text mode here,
3684 // and math commands may be invalid (bug 6797)
3686 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3687 rem, Encodings::TEXT_CMD);
3690 cerr << "When parsing " << t.cs()
3691 << ", result is " << to_utf8(s)
3692 << "+" << to_utf8(rem) << endl;
3693 context.check_layout(os);
3695 skip_spaces_braces(p);
3697 //cerr << "#: " << t << " mode: " << mode << endl;
3698 // heuristic: read up to next non-nested space
3700 string s = t.asInput();
3701 string z = p.verbatim_item();
3702 while (p.good() && z != " " && z.size()) {
3703 //cerr << "read: " << z << endl;
3705 z = p.verbatim_item();
3707 cerr << "found ERT: " << s << endl;
3708 handle_ert(os, s + ' ', context);
3711 string name = t.asInput();
3712 if (p.next_token().asInput() == "*") {
3713 // Starred commands like \vspace*{}
3714 p.get_token(); // Eat '*'
3717 if (!parse_command(name, p, os, outer, context))
3718 handle_ert(os, name, context);
3722 if (flags & FLAG_LEAVE) {
3723 flags &= ~FLAG_LEAVE;