2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context, InsetLayout const * layout)
46 bool const forcePlainLayout =
47 layout ? layout->forcePlainLayout() : false;
48 Context newcontext(true, context.textclass);
50 newcontext.layout = &context.textclass.plainLayout();
52 newcontext.font = context.font;
53 parse_text(p, os, flags, outer, newcontext);
54 newcontext.check_end_layout(os);
60 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
61 Context const & context, string const & name)
63 InsetLayout const * layout = 0;
64 DocumentClass::InsetLayouts::const_iterator it =
65 context.textclass.insetLayouts().find(from_ascii(name));
66 if (it != context.textclass.insetLayouts().end())
67 layout = &(it->second);
68 parse_text_in_inset(p, os, flags, outer, context, layout);
71 /// parses a paragraph snippet, useful for example for \\emph{...}
72 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
75 Context newcontext(context);
76 // Don't inherit the paragraph-level extra stuff
77 newcontext.par_extra_stuff.clear();
78 parse_text(p, os, flags, outer, newcontext);
79 // Make sure that we don't create invalid .lyx files
80 context.need_layout = newcontext.need_layout;
81 context.need_end_layout = newcontext.need_end_layout;
86 * Thin wrapper around parse_text_snippet() using a string.
88 * We completely ignore \c context.need_layout and \c context.need_end_layout,
89 * because our return value is not used directly (otherwise the stream version
90 * of parse_text_snippet() could be used). That means that the caller needs
91 * to do layout management manually.
92 * This is intended to parse text that does not create any layout changes.
94 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
97 Context newcontext(context);
98 newcontext.need_layout = false;
99 newcontext.need_end_layout = false;
100 newcontext.new_layout_allowed = false;
101 // Avoid warning by Context::~Context()
102 newcontext.par_extra_stuff.clear();
104 parse_text_snippet(p, os, flags, outer, newcontext);
109 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
110 "vpageref", "prettyref", "eqref", 0 };
114 * The starred forms are also known except for "citefullauthor",
115 * "citeyear" and "citeyearpar".
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * No starred form other than "cite*" known.
125 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
126 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
127 // jurabib commands not (yet) supported by LyX:
129 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
130 // "footciteauthor", "footciteyear", "footciteyearpar",
131 "citefield", "citetitle", 0 };
133 /// LaTeX names for quotes
134 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
135 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
136 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
137 "guilsinglleft", "frq", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
141 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
142 "gld", "grd", "gls", "ers", "fls",
143 "fls", "frs", "frs", 0};
145 /// LaTeX names for font sizes
146 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
147 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
149 /// the same as known_sizes with .lyx names
150 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
151 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
153 /// LaTeX 2.09 names for font families
154 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
156 /// LaTeX names for font families
157 char const * const known_font_families[] = { "rmfamily", "sffamily",
160 /// the same as known_old_font_families and known_font_families with .lyx names
161 char const * const known_coded_font_families[] = { "roman", "sans",
164 /// LaTeX 2.09 names for font series
165 char const * const known_old_font_series[] = { "bf", 0};
167 /// LaTeX names for font series
168 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
170 /// the same as known_old_font_series and known_font_series with .lyx names
171 char const * const known_coded_font_series[] = { "bold", "medium", 0};
173 /// LaTeX 2.09 names for font shapes
174 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
176 /// LaTeX names for font shapes
177 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
180 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
181 char const * const known_coded_font_shapes[] = { "italic", "slanted",
182 "smallcaps", "up", 0};
185 * Graphics file extensions known by the dvips driver of the graphics package.
186 * These extensions are used to complete the filename of an included
187 * graphics file if it does not contain an extension.
188 * The order must be the same that latex uses to find a file, because we
189 * will use the first extension that matches.
190 * This is only an approximation for the common cases. If we would want to
191 * do it right in all cases, we would need to know which graphics driver is
192 * used and know the extensions of every driver of the graphics package.
194 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
195 "ps.gz", "eps.Z", "ps.Z", 0};
198 * Graphics file extensions known by the pdftex driver of the graphics package.
199 * \sa known_dvips_graphics_formats
201 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
205 * Known file extensions for TeX files as used by \\include.
207 char const * const known_tex_extensions[] = {"tex", 0};
209 /// spaces known by InsetSpace
210 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
211 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
212 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
214 /// the same as known_spaces with .lyx names
215 char const * const known_coded_spaces[] = { "space{}", "space{}",
216 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
217 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
218 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
220 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
221 /// them in ERT. "LaTeXe" must come before "LaTeX"!
222 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
223 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
224 int const known_phrase_lengths[] = {3, 5, 7, 0};
227 /// splits "x=z, y=b" into a map and an ordered keyword vector
228 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
233 keys.resize(v.size());
234 for (size_t i = 0; i < v.size(); ++i) {
235 size_t const pos = v[i].find('=');
236 string const index = trim(v[i].substr(0, pos));
237 string const value = trim(v[i].substr(pos + 1, string::npos));
245 * Split a LaTeX length into value and unit.
246 * The latter can be a real unit like "pt", or a latex length variable
247 * like "\textwidth". The unit may contain additional stuff like glue
248 * lengths, but we don't care, because such lengths are ERT anyway.
249 * \returns true if \p value and \p unit are valid.
251 bool splitLatexLength(string const & len, string & value, string & unit)
255 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
256 //'4,5' is a valid LaTeX length number. Change it to '4.5'
257 string const length = subst(len, ',', '.');
258 if (i == string::npos)
261 if (len[0] == '\\') {
262 // We had something like \textwidth without a factor
268 value = trim(string(length, 0, i));
272 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
273 if (contains(len, '\\'))
274 unit = trim(string(len, i));
276 unit = ascii_lowercase(trim(string(len, i)));
281 /// A simple function to translate a latex length to something LyX can
282 /// understand. Not perfect, but rather best-effort.
283 bool translate_len(string const & length, string & valstring, string & unit)
285 if (!splitLatexLength(length, valstring, unit))
287 // LyX uses percent values
289 istringstream iss(valstring);
294 string const percentval = oss.str();
296 if (unit.empty() || unit[0] != '\\')
298 string::size_type const i = unit.find(' ');
299 string const endlen = (i == string::npos) ? string() : string(unit, i);
300 if (unit == "\\textwidth") {
301 valstring = percentval;
302 unit = "text%" + endlen;
303 } else if (unit == "\\columnwidth") {
304 valstring = percentval;
305 unit = "col%" + endlen;
306 } else if (unit == "\\paperwidth") {
307 valstring = percentval;
308 unit = "page%" + endlen;
309 } else if (unit == "\\linewidth") {
310 valstring = percentval;
311 unit = "line%" + endlen;
312 } else if (unit == "\\paperheight") {
313 valstring = percentval;
314 unit = "pheight%" + endlen;
315 } else if (unit == "\\textheight") {
316 valstring = percentval;
317 unit = "theight%" + endlen;
325 string translate_len(string const & length)
329 if (translate_len(length, value, unit))
331 // If the input is invalid, return what we have.
339 * Translates a LaTeX length into \p value, \p unit and
340 * \p special parts suitable for a box inset.
341 * The difference from translate_len() is that a box inset knows about
342 * some special "units" that are stored in \p special.
344 void translate_box_len(string const & length, string & value, string & unit, string & special)
346 if (translate_len(length, value, unit)) {
347 if (unit == "\\height" || unit == "\\depth" ||
348 unit == "\\totalheight" || unit == "\\width") {
349 special = unit.substr(1);
350 // The unit is not used, but LyX requires a dummy setting
363 * Find a file with basename \p name in path \p path and an extension
366 string find_file(string const & name, string const & path,
367 char const * const * extensions)
369 for (char const * const * what = extensions; *what; ++what) {
370 string const trial = addExtension(name, *what);
371 if (makeAbsPath(trial, path).exists())
378 void begin_inset(ostream & os, string const & name)
380 os << "\n\\begin_inset " << name;
384 void begin_command_inset(ostream & os, string const & name,
385 string const & latexname)
387 begin_inset(os, "CommandInset ");
388 os << name << "\nLatexCommand " << latexname << '\n';
392 void end_inset(ostream & os)
394 os << "\n\\end_inset\n\n";
398 bool skip_braces(Parser & p)
400 if (p.next_token().cat() != catBegin)
403 if (p.next_token().cat() == catEnd) {
412 /// replace LaTeX commands in \p s from the unicodesymbols file with their
414 docstring convert_unicodesymbols(docstring s)
417 for (size_t i = 0; i < s.size();) {
424 docstring parsed = encodings.fromLaTeXCommand(s, rem,
425 Encodings::TEXT_CMD);
428 if (s.empty() || s[0] != '\\')
437 /// try to convert \p s to a valid InsetCommand argument
438 string convert_command_inset_arg(string s)
441 // since we don't know the input encoding we can't use from_utf8
442 s = to_utf8(convert_unicodesymbols(from_ascii(s)));
443 // LyX cannot handle newlines in a latex command
444 return subst(s, "\n", " ");
448 void handle_backslash(ostream & os, string const & s)
450 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
452 os << "\n\\backslash\n";
459 void handle_ert(ostream & os, string const & s, Context & context)
461 // We must have a valid layout before outputting the ERT inset.
462 context.check_layout(os);
463 Context newcontext(true, context.textclass);
464 begin_inset(os, "ERT");
465 os << "\nstatus collapsed\n";
466 newcontext.check_layout(os);
467 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
469 os << "\n\\backslash\n";
470 else if (*it == '\n') {
471 newcontext.new_paragraph(os);
472 newcontext.check_layout(os);
476 newcontext.check_end_layout(os);
481 void handle_comment(ostream & os, string const & s, Context & context)
483 // TODO: Handle this better
484 Context newcontext(true, context.textclass);
485 begin_inset(os, "ERT");
486 os << "\nstatus collapsed\n";
487 newcontext.check_layout(os);
488 handle_backslash(os, s);
489 // make sure that our comment is the last thing on the line
490 newcontext.new_paragraph(os);
491 newcontext.check_layout(os);
492 newcontext.check_end_layout(os);
497 Layout const * findLayout(TextClass const & textclass, string const & name, bool command)
499 Layout const * layout = findLayoutWithoutModule(textclass, name, command);
502 if (checkModule(name, command))
503 return findLayoutWithoutModule(textclass, name, command);
508 InsetLayout const * findInsetLayout(TextClass const & textclass, string const & name, bool command)
510 InsetLayout const * insetlayout = findInsetLayoutWithoutModule(textclass, name, command);
513 if (checkModule(name, command))
514 return findInsetLayoutWithoutModule(textclass, name, command);
519 void eat_whitespace(Parser &, ostream &, Context &, bool);
523 * Skips whitespace and braces.
524 * This should be called after a command has been parsed that is not put into
525 * ERT, and where LyX adds "{}" if needed.
527 void skip_spaces_braces(Parser & p, bool keepws = false)
529 /* The following four examples produce the same typeset output and
530 should be handled by this function:
538 // Unfortunately we need to skip comments, too.
539 // We can't use eat_whitespace since writing them after the {}
540 // results in different output in some cases.
541 bool const skipped_spaces = p.skip_spaces(true);
542 bool const skipped_braces = skip_braces(p);
543 if (keepws && skipped_spaces && !skipped_braces)
544 // put back the space (it is better handled by check_space)
545 p.unskip_spaces(true);
549 void output_command_layout(ostream & os, Parser & p, bool outer,
550 Context & parent_context,
551 Layout const * newlayout)
553 TeXFont const oldFont = parent_context.font;
554 // save the current font size
555 string const size = oldFont.size;
556 // reset the font size to default, because the font size switches
557 // don't affect section headings and the like
558 parent_context.font.size = Context::normalfont.size;
559 // we only need to write the font change if we have an open layout
560 if (!parent_context.atParagraphStart())
561 output_font_change(os, oldFont, parent_context.font);
562 parent_context.check_end_layout(os);
563 Context context(true, parent_context.textclass, newlayout,
564 parent_context.layout, parent_context.font);
565 if (parent_context.deeper_paragraph) {
566 // We are beginning a nested environment after a
567 // deeper paragraph inside the outer list environment.
568 // Therefore we don't need to output a "begin deeper".
569 context.need_end_deeper = true;
571 context.check_deeper(os);
572 context.check_layout(os);
573 unsigned int optargs = 0;
574 while (optargs < context.layout->optargs) {
575 eat_whitespace(p, os, context, false);
576 if (p.next_token().cat() == catEscape ||
577 p.next_token().character() != '[')
579 p.get_token(); // eat '['
580 begin_inset(os, "OptArg\n");
581 os << "status collapsed\n\n";
582 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
584 eat_whitespace(p, os, context, false);
587 unsigned int reqargs = 0;
588 while (LYX_FORMAT >= 392 && reqargs < context.layout->reqargs) {
589 eat_whitespace(p, os, context, false);
590 if (p.next_token().cat() != catBegin)
592 p.get_token(); // eat '{'
593 begin_inset(os, "OptArg\n");
594 os << "status collapsed\n\n";
595 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
597 eat_whitespace(p, os, context, false);
600 parse_text(p, os, FLAG_ITEM, outer, context);
601 context.check_end_layout(os);
602 if (parent_context.deeper_paragraph) {
603 // We must suppress the "end deeper" because we
604 // suppressed the "begin deeper" above.
605 context.need_end_deeper = false;
607 context.check_end_deeper(os);
608 // We don't need really a new paragraph, but
609 // we must make sure that the next item gets a \begin_layout.
610 parent_context.new_paragraph(os);
611 // Set the font size to the original value. No need to output it here
612 // (Context::begin_layout() will do that if needed)
613 parent_context.font.size = size;
618 * Output a space if necessary.
619 * This function gets called for every whitespace token.
621 * We have three cases here:
622 * 1. A space must be suppressed. Example: The lyxcode case below
623 * 2. A space may be suppressed. Example: Spaces before "\par"
624 * 3. A space must not be suppressed. Example: A space between two words
626 * We currently handle only 1. and 3 and from 2. only the case of
627 * spaces before newlines as a side effect.
629 * 2. could be used to suppress as many spaces as possible. This has two effects:
630 * - Reimporting LyX generated LaTeX files changes almost no whitespace
631 * - Superflous whitespace from non LyX generated LaTeX files is removed.
632 * The drawback is that the logic inside the function becomes
633 * complicated, and that is the reason why it is not implemented.
635 void check_space(Parser & p, ostream & os, Context & context)
637 Token const next = p.next_token();
638 Token const curr = p.curr_token();
639 // A space before a single newline and vice versa must be ignored
640 // LyX emits a newline before \end{lyxcode}.
641 // This newline must be ignored,
642 // otherwise LyX will add an additional protected space.
643 if (next.cat() == catSpace ||
644 next.cat() == catNewline ||
645 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
648 context.check_layout(os);
654 * Parse all arguments of \p command
656 void parse_arguments(string const & command,
657 vector<ArgumentType> const & template_arguments,
658 Parser & p, ostream & os, bool outer, Context & context)
660 string ert = command;
661 size_t no_arguments = template_arguments.size();
662 for (size_t i = 0; i < no_arguments; ++i) {
663 switch (template_arguments[i]) {
665 // This argument contains regular LaTeX
666 handle_ert(os, ert + '{', context);
667 eat_whitespace(p, os, context, false);
668 parse_text(p, os, FLAG_ITEM, outer, context);
672 // This argument consists only of a single item.
673 // The presence of '{' or not must be preserved.
675 if (p.next_token().cat() == catBegin)
676 ert += '{' + p.verbatim_item() + '}';
678 ert += p.verbatim_item();
681 // This argument may contain special characters
682 ert += '{' + p.verbatim_item() + '}';
685 // true because we must not eat whitespace
686 // if an optional arg follows me must not strip the
687 // brackets from this one
688 if (i < no_arguments - 1 &&
689 template_arguments[i+1] == optional)
690 ert += p.getFullOpt(true);
692 ert += p.getOpt(true);
696 handle_ert(os, ert, context);
701 * Check whether \p command is a known command. If yes,
702 * handle the command with all arguments.
703 * \return true if the command was parsed, false otherwise.
705 bool parse_command(string const & command, Parser & p, ostream & os,
706 bool outer, Context & context)
708 if (known_commands.find(command) != known_commands.end()) {
709 parse_arguments(command, known_commands[command], p, os,
717 /// Parses a minipage or parbox
718 void parse_box(Parser & p, ostream & os, unsigned outer_flags,
719 unsigned inner_flags, bool outer, Context & parent_context,
720 string const & outer_type, string const & special,
721 string const & inner_type)
725 string hor_pos = "c";
726 // We need to set the height to the LaTeX default of 1\\totalheight
727 // for the case when no height argument is given
728 string height_value = "1";
729 string height_unit = "in";
730 string height_special = "totalheight";
732 if (!inner_type.empty() && p.hasOpt()) {
733 position = p.getArg('[', ']');
734 if (position != "t" && position != "c" && position != "b") {
735 cerr << "invalid position " << position << " for "
736 << inner_type << endl;
740 latex_height = p.getArg('[', ']');
741 translate_box_len(latex_height, height_value, height_unit, height_special);
744 inner_pos = p.getArg('[', ']');
745 if (inner_pos != "c" && inner_pos != "t" &&
746 inner_pos != "b" && inner_pos != "s") {
747 cerr << "invalid inner_pos "
748 << inner_pos << " for "
749 << inner_type << endl;
750 inner_pos = position;
758 if (inner_type.empty()) {
760 latex_width = "\\columnwidth";
763 latex_width = p2.getArg('[', ']');
764 string const opt = p2.getArg('[', ']');
767 if (hor_pos != "l" && hor_pos != "c" &&
769 cerr << "invalid hor_pos " << hor_pos
770 << " for " << outer_type << endl;
776 latex_width = p.verbatim_item();
777 translate_len(latex_width, width_value, width_unit);
778 // LyX can't handle length variables
779 bool use_ert = contains(width_unit, '\\') || contains(height_unit, '\\');
780 if (!use_ert && !outer_type.empty() && !inner_type.empty()) {
781 // Look whether there is some content after the end of the
782 // inner box, but before the end of the outer box.
783 // If yes, we need to output ERT.
785 if (inner_flags & FLAG_END)
786 p.verbatimEnvironment(inner_type);
790 if ((outer_type == "framed" && p.next_token().asInput() != "\\end") ||
791 (outer_type != "framed" && p.next_token().cat() != catEnd)) {
792 // something is between the end of the inner box and
793 // the end of the outer box, so we need to use ERT.
800 if (!outer_type.empty()) {
801 if (outer_flags & FLAG_END)
802 ss << "\\begin{" << outer_type << '}';
804 ss << '\\' << outer_type << '{';
805 if (!special.empty())
809 if (!inner_type.empty()) {
810 if (inner_flags & FLAG_END)
811 ss << "\\begin{" << inner_type << '}';
813 ss << '\\' << inner_type;
814 if (!position.empty())
815 ss << '[' << position << ']';
816 if (!latex_height.empty())
817 ss << '[' << latex_height << ']';
818 if (!inner_pos.empty())
819 ss << '[' << inner_pos << ']';
820 ss << '{' << latex_width << '}';
821 if (!(inner_flags & FLAG_END))
824 handle_ert(os, ss.str(), parent_context);
825 if (!inner_type.empty()) {
826 parse_text(p, os, inner_flags, outer, parent_context);
827 if (inner_flags & FLAG_END)
828 handle_ert(os, "\\end{" + inner_type + '}',
831 handle_ert(os, "}", parent_context);
833 if (!outer_type.empty()) {
834 parse_text(p, os, outer_flags, outer, parent_context);
835 if (outer_flags & FLAG_END)
836 handle_ert(os, "\\end{" + outer_type + '}',
839 handle_ert(os, "}", parent_context);
842 // LyX does not like empty positions, so we have
843 // to set them to the LaTeX default values here.
844 if (position.empty())
846 if (inner_pos.empty())
847 inner_pos = position;
848 parent_context.check_layout(os);
849 begin_inset(os, "Box ");
850 if (outer_type == "framed")
852 else if (outer_type == "framebox")
854 else if (outer_type == "shadowbox")
856 else if (outer_type == "shaded")
858 else if (outer_type == "doublebox")
860 else if (outer_type.empty())
863 os << outer_type << '\n';
864 os << "position \"" << position << "\"\n";
865 os << "hor_pos \"" << hor_pos << "\"\n";
866 os << "has_inner_box " << !inner_type.empty() << "\n";
867 os << "inner_pos \"" << inner_pos << "\"\n";
868 os << "use_parbox " << (inner_type == "parbox") << '\n';
869 os << "width \"" << width_value << width_unit << "\"\n";
870 os << "special \"none\"\n";
871 os << "height \"" << height_value << height_unit << "\"\n";
872 os << "height_special \"" << height_special << "\"\n";
873 os << "status open\n\n";
874 Context context(true, parent_context.textclass);
875 context.font = parent_context.font;
877 // If we have no inner box the contens will be read with the outer box
878 if (!inner_type.empty())
879 parse_text(p, os, inner_flags, outer, context);
881 // Ensure that the end of the outer box is parsed correctly:
882 // The opening brace has been eaten by parse_outer_box()
883 if (!outer_type.empty() && (outer_flags & FLAG_ITEM)) {
884 outer_flags &= ~FLAG_ITEM;
885 outer_flags |= FLAG_BRACE_LAST;
888 // Find end of outer box, output contents if inner_type is
889 // empty and output possible comments
890 if (!outer_type.empty()) {
891 // This does not output anything but comments if
892 // inner_type is not empty (see use_ert)
893 parse_text(p, os, outer_flags, outer, context);
896 context.check_end_layout(os);
898 #ifdef PRESERVE_LAYOUT
899 // LyX puts a % after the end of the minipage
900 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
902 //handle_comment(os, "%dummy", parent_context);
905 parent_context.new_paragraph(os);
907 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
908 //handle_comment(os, "%dummy", parent_context);
911 // We add a protected space if something real follows
912 if (p.good() && p.next_token().cat() != catComment) {
913 begin_inset(os, "space ~\n");
922 void parse_outer_box(Parser & p, ostream & os, unsigned flags, bool outer,
923 Context & parent_context, string const & outer_type,
924 string const & special)
926 eat_whitespace(p, os, parent_context, false);
927 if (flags & FLAG_ITEM) {
929 if (p.next_token().cat() == catBegin)
932 cerr << "Warning: Ignoring missing '{' after \\"
933 << outer_type << '.' << endl;
934 eat_whitespace(p, os, parent_context, false);
937 unsigned int inner_flags = 0;
938 if (outer_type == "shaded") {
939 // These boxes never have an inner box
941 } else if (p.next_token().asInput() == "\\parbox") {
942 inner = p.get_token().cs();
943 inner_flags = FLAG_ITEM;
944 } else if (p.next_token().asInput() == "\\begin") {
945 // Is this a minipage?
948 inner = p.getArg('{', '}');
950 if (inner == "minipage") {
953 eat_whitespace(p, os, parent_context, false);
954 inner_flags = FLAG_END;
958 if (inner_flags == FLAG_END) {
959 active_environments.push_back(inner);
960 parse_box(p, os, flags, FLAG_END, outer, parent_context,
961 outer_type, special, inner);
962 active_environments.pop_back();
964 parse_box(p, os, flags, inner_flags, outer, parent_context,
965 outer_type, special, inner);
970 void parse_listings(Parser & p, ostream & os, Context & parent_context)
972 parent_context.check_layout(os);
973 begin_inset(os, "listings\n");
974 os << "inline false\n"
975 << "status collapsed\n";
976 Context context(true, parent_context.textclass);
977 context.layout = &parent_context.textclass.plainLayout();
978 context.check_layout(os);
979 string const s = p.verbatimEnvironment("lstlisting");
980 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
982 os << "\n\\backslash\n";
983 else if (*it == '\n') {
984 // avoid adding an empty paragraph at the end
986 context.new_paragraph(os);
987 context.check_layout(os);
992 context.check_end_layout(os);
997 /// parse an unknown environment
998 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
999 unsigned flags, bool outer,
1000 Context & parent_context)
1002 if (name == "tabbing")
1003 // We need to remember that we have to handle '\=' specially
1004 flags |= FLAG_TABBING;
1006 // We need to translate font changes and paragraphs inside the
1007 // environment to ERT if we have a non standard font.
1008 // Otherwise things like
1009 // \large\begin{foo}\huge bar\end{foo}
1011 bool const specialfont =
1012 (parent_context.font != parent_context.normalfont);
1013 bool const new_layout_allowed = parent_context.new_layout_allowed;
1015 parent_context.new_layout_allowed = false;
1016 handle_ert(os, "\\begin{" + name + "}", parent_context);
1017 parse_text_snippet(p, os, flags, outer, parent_context);
1018 handle_ert(os, "\\end{" + name + "}", parent_context);
1020 parent_context.new_layout_allowed = new_layout_allowed;
1024 void parse_environment(Parser & p, ostream & os, bool outer,
1025 string & last_env, Context & parent_context)
1027 Layout const * newlayout;
1028 InsetLayout const * newinsetlayout = 0;
1029 string const name = p.getArg('{', '}');
1030 const bool is_starred = suffixIs(name, '*');
1031 string const unstarred_name = rtrim(name, "*");
1032 active_environments.push_back(name);
1034 if (is_math_env(name)) {
1035 parent_context.check_layout(os);
1036 begin_inset(os, "Formula ");
1037 os << "\\begin{" << name << "}";
1038 parse_math(p, os, FLAG_END, MATH_MODE);
1039 os << "\\end{" << name << "}";
1043 else if (name == "tabular" || name == "longtable") {
1044 eat_whitespace(p, os, parent_context, false);
1045 parent_context.check_layout(os);
1046 begin_inset(os, "Tabular ");
1047 handle_tabular(p, os, name == "longtable", parent_context);
1052 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
1053 eat_whitespace(p, os, parent_context, false);
1054 parent_context.check_layout(os);
1055 begin_inset(os, "Float " + unstarred_name + "\n");
1057 os << "placement " << p.getArg('[', ']') << '\n';
1058 os << "wide " << convert<string>(is_starred)
1059 << "\nsideways false"
1060 << "\nstatus open\n\n";
1061 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1063 // We don't need really a new paragraph, but
1064 // we must make sure that the next item gets a \begin_layout.
1065 parent_context.new_paragraph(os);
1069 else if (name == "minipage") {
1070 eat_whitespace(p, os, parent_context, false);
1071 parse_box(p, os, 0, FLAG_END, outer, parent_context, "", "", name);
1075 else if (name == "comment") {
1076 eat_whitespace(p, os, parent_context, false);
1077 parent_context.check_layout(os);
1078 begin_inset(os, "Note Comment\n");
1079 os << "status open\n";
1080 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1083 skip_braces(p); // eat {} that might by set by LyX behind comments
1086 else if (name == "lyxgreyedout") {
1087 eat_whitespace(p, os, parent_context, false);
1088 parent_context.check_layout(os);
1089 begin_inset(os, "Note Greyedout\n");
1090 os << "status open\n";
1091 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
1096 else if (name == "framed" || name == "shaded") {
1097 eat_whitespace(p, os, parent_context, false);
1098 parse_outer_box(p, os, FLAG_END, outer, parent_context, name, "");
1102 else if (name == "lstlisting") {
1103 eat_whitespace(p, os, parent_context, false);
1104 // FIXME handle listings with parameters
1106 parse_unknown_environment(p, name, os, FLAG_END,
1107 outer, parent_context);
1109 parse_listings(p, os, parent_context);
1113 else if (!parent_context.new_layout_allowed)
1114 parse_unknown_environment(p, name, os, FLAG_END, outer,
1117 // Alignment and spacing settings
1118 // FIXME (bug xxxx): These settings can span multiple paragraphs and
1119 // therefore are totally broken!
1120 // Note that \centering, raggedright, and raggedleft cannot be handled, as
1121 // they are commands not environments. They are furthermore switches that
1122 // can be ended by another switches, but also by commands like \footnote or
1123 // \parbox. So the only safe way is to leave them untouched.
1124 else if (name == "center" || name == "centering" ||
1125 name == "flushleft" || name == "flushright" ||
1126 name == "singlespace" || name == "onehalfspace" ||
1127 name == "doublespace" || name == "spacing") {
1128 eat_whitespace(p, os, parent_context, false);
1129 // We must begin a new paragraph if not already done
1130 if (! parent_context.atParagraphStart()) {
1131 parent_context.check_end_layout(os);
1132 parent_context.new_paragraph(os);
1134 if (name == "flushleft")
1135 parent_context.add_extra_stuff("\\align left\n");
1136 else if (name == "flushright")
1137 parent_context.add_extra_stuff("\\align right\n");
1138 else if (name == "center" || name == "centering")
1139 parent_context.add_extra_stuff("\\align center\n");
1140 else if (name == "singlespace")
1141 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
1142 else if (name == "onehalfspace")
1143 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
1144 else if (name == "doublespace")
1145 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
1146 else if (name == "spacing")
1147 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
1148 parse_text(p, os, FLAG_END, outer, parent_context);
1149 // Just in case the environment is empty
1150 parent_context.extra_stuff.erase();
1151 // We must begin a new paragraph to reset the alignment
1152 parent_context.new_paragraph(os);
1156 // The single '=' is meant here.
1157 else if ((newlayout = findLayout(parent_context.textclass, name, false))) {
1158 eat_whitespace(p, os, parent_context, false);
1159 Context context(true, parent_context.textclass, newlayout,
1160 parent_context.layout, parent_context.font);
1161 if (parent_context.deeper_paragraph) {
1162 // We are beginning a nested environment after a
1163 // deeper paragraph inside the outer list environment.
1164 // Therefore we don't need to output a "begin deeper".
1165 context.need_end_deeper = true;
1167 parent_context.check_end_layout(os);
1168 if (last_env == name) {
1169 // we need to output a separator since LyX would export
1170 // the two environments as one otherwise (bug 5716)
1171 docstring const sep = from_ascii("--Separator--");
1172 TeX2LyXDocClass const & textclass(parent_context.textclass);
1173 if (textclass.hasLayout(sep)) {
1174 Context newcontext(parent_context);
1175 newcontext.layout = &(textclass[sep]);
1176 newcontext.check_layout(os);
1177 newcontext.check_end_layout(os);
1179 parent_context.check_layout(os);
1180 begin_inset(os, "Note Note\n");
1181 os << "status closed\n";
1182 Context newcontext(true, textclass,
1183 &(textclass.defaultLayout()));
1184 newcontext.check_layout(os);
1185 newcontext.check_end_layout(os);
1187 parent_context.check_end_layout(os);
1190 switch (context.layout->latextype) {
1191 case LATEX_LIST_ENVIRONMENT:
1192 context.add_par_extra_stuff("\\labelwidthstring "
1193 + p.verbatim_item() + '\n');
1196 case LATEX_BIB_ENVIRONMENT:
1197 p.verbatim_item(); // swallow next arg
1203 context.check_deeper(os);
1204 parse_text(p, os, FLAG_END, outer, context);
1205 context.check_end_layout(os);
1206 if (parent_context.deeper_paragraph) {
1207 // We must suppress the "end deeper" because we
1208 // suppressed the "begin deeper" above.
1209 context.need_end_deeper = false;
1211 context.check_end_deeper(os);
1212 parent_context.new_paragraph(os);
1216 // The single '=' is meant here.
1217 else if ((newinsetlayout = findInsetLayout(parent_context.textclass, name, false))) {
1218 eat_whitespace(p, os, parent_context, false);
1219 parent_context.check_layout(os);
1220 begin_inset(os, "Flex ");
1221 os << to_utf8(newinsetlayout->name()) << '\n'
1222 << "status collapsed\n";
1223 parse_text_in_inset(p, os, FLAG_END, false, parent_context, newinsetlayout);
1227 else if (name == "appendix") {
1228 // This is no good latex style, but it works and is used in some documents...
1229 eat_whitespace(p, os, parent_context, false);
1230 parent_context.check_end_layout(os);
1231 Context context(true, parent_context.textclass, parent_context.layout,
1232 parent_context.layout, parent_context.font);
1233 context.check_layout(os);
1234 os << "\\start_of_appendix\n";
1235 parse_text(p, os, FLAG_END, outer, context);
1236 context.check_end_layout(os);
1240 else if (known_environments.find(name) != known_environments.end()) {
1241 vector<ArgumentType> arguments = known_environments[name];
1242 // The last "argument" denotes wether we may translate the
1243 // environment contents to LyX
1244 // The default required if no argument is given makes us
1245 // compatible with the reLyXre environment.
1246 ArgumentType contents = arguments.empty() ?
1249 if (!arguments.empty())
1250 arguments.pop_back();
1251 // See comment in parse_unknown_environment()
1252 bool const specialfont =
1253 (parent_context.font != parent_context.normalfont);
1254 bool const new_layout_allowed =
1255 parent_context.new_layout_allowed;
1257 parent_context.new_layout_allowed = false;
1258 parse_arguments("\\begin{" + name + "}", arguments, p, os,
1259 outer, parent_context);
1260 if (contents == verbatim)
1261 handle_ert(os, p.verbatimEnvironment(name),
1264 parse_text_snippet(p, os, FLAG_END, outer,
1266 handle_ert(os, "\\end{" + name + "}", parent_context);
1268 parent_context.new_layout_allowed = new_layout_allowed;
1272 parse_unknown_environment(p, name, os, FLAG_END, outer,
1276 active_environments.pop_back();
1280 /// parses a comment and outputs it to \p os.
1281 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1283 LASSERT(t.cat() == catComment, return);
1284 if (!t.cs().empty()) {
1285 context.check_layout(os);
1286 handle_comment(os, '%' + t.cs(), context);
1287 if (p.next_token().cat() == catNewline) {
1288 // A newline after a comment line starts a new
1290 if (context.new_layout_allowed) {
1291 if(!context.atParagraphStart())
1292 // Only start a new paragraph if not already
1293 // done (we might get called recursively)
1294 context.new_paragraph(os);
1296 handle_ert(os, "\n", context);
1297 eat_whitespace(p, os, context, true);
1300 // "%\n" combination
1307 * Reads spaces and comments until the first non-space, non-comment token.
1308 * New paragraphs (double newlines or \\par) are handled like simple spaces
1309 * if \p eatParagraph is true.
1310 * Spaces are skipped, but comments are written to \p os.
1312 void eat_whitespace(Parser & p, ostream & os, Context & context,
1316 Token const & t = p.get_token();
1317 if (t.cat() == catComment)
1318 parse_comment(p, os, t, context);
1319 else if ((! eatParagraph && p.isParagraph()) ||
1320 (t.cat() != catSpace && t.cat() != catNewline)) {
1329 * Set a font attribute, parse text and reset the font attribute.
1330 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1331 * \param currentvalue Current value of the attribute. Is set to the new
1332 * value during parsing.
1333 * \param newvalue New value of the attribute
1335 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1336 Context & context, string const & attribute,
1337 string & currentvalue, string const & newvalue)
1339 context.check_layout(os);
1340 string const oldvalue = currentvalue;
1341 currentvalue = newvalue;
1342 os << '\n' << attribute << ' ' << newvalue << "\n";
1343 parse_text_snippet(p, os, flags, outer, context);
1344 context.check_layout(os);
1345 os << '\n' << attribute << ' ' << oldvalue << "\n";
1346 currentvalue = oldvalue;
1350 /// get the arguments of a natbib or jurabib citation command
1351 void get_cite_arguments(Parser & p, bool natbibOrder,
1352 string & before, string & after)
1354 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1356 // text before the citation
1358 // text after the citation
1359 after = p.getFullOpt();
1361 if (!after.empty()) {
1362 before = p.getFullOpt();
1363 if (natbibOrder && !before.empty())
1364 swap(before, after);
1369 /// Convert filenames with TeX macros and/or quotes to something LyX
1371 string const normalize_filename(string const & name)
1373 Parser p(trim(name, "\""));
1376 Token const & t = p.get_token();
1377 if (t.cat() != catEscape)
1379 else if (t.cs() == "lyxdot") {
1380 // This is used by LyX for simple dots in relative
1384 } else if (t.cs() == "space") {
1394 /// Convert \p name from TeX convention (relative to master file) to LyX
1395 /// convention (relative to .lyx file) if it is relative
1396 void fix_relative_filename(string & name)
1398 if (FileName::isAbsolute(name))
1401 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1402 from_utf8(getParentFilePath())));
1406 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1407 void parse_noweb(Parser & p, ostream & os, Context & context)
1409 // assemble the rest of the keyword
1413 Token const & t = p.get_token();
1414 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1417 scrap = (p.good() && p.next_token().asInput() == "=");
1419 name += p.get_token().asInput();
1422 name += t.asInput();
1425 if (!scrap || !context.new_layout_allowed ||
1426 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1427 cerr << "Warning: Could not interpret '" << name
1428 << "'. Ignoring it." << endl;
1432 // We use new_paragraph instead of check_end_layout because the stuff
1433 // following the noweb chunk needs to start with a \begin_layout.
1434 // This may create a new paragraph even if there was none in the
1435 // noweb file, but the alternative is an invalid LyX file. Since
1436 // noweb code chunks are implemented with a layout style in LyX they
1437 // always must be in an own paragraph.
1438 context.new_paragraph(os);
1439 Context newcontext(true, context.textclass,
1440 &context.textclass[from_ascii("Scrap")]);
1441 newcontext.check_layout(os);
1444 Token const & t = p.get_token();
1445 // We abuse the parser a bit, because this is no TeX syntax
1447 if (t.cat() == catEscape)
1448 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1451 begin_inset(oss, "Newline newline");
1453 os << subst(t.asInput(), "\n", oss.str());
1455 // The scrap chunk is ended by an @ at the beginning of a line.
1456 // After the @ the line may contain a comment and/or
1457 // whitespace, but nothing else.
1458 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1459 (p.next_token().cat() == catSpace ||
1460 p.next_token().cat() == catNewline ||
1461 p.next_token().cat() == catComment)) {
1462 while (p.good() && p.next_token().cat() == catSpace)
1463 os << p.get_token().asInput();
1464 if (p.next_token().cat() == catComment)
1465 // The comment includes a final '\n'
1466 os << p.get_token().asInput();
1468 if (p.next_token().cat() == catNewline)
1475 newcontext.check_end_layout(os);
1479 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1480 bool is_macro(Parser & p)
1482 Token first = p.curr_token();
1483 if (first.cat() != catEscape || !p.good())
1485 if (first.cs() == "def")
1487 if (first.cs() != "global" && first.cs() != "long")
1489 Token second = p.get_token();
1491 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1492 second.cat() == catNewline || second.cat() == catComment)) {
1493 second = p.get_token();
1496 bool secondvalid = second.cat() == catEscape;
1498 bool thirdvalid = false;
1499 if (p.good() && first.cs() == "global" && secondvalid &&
1500 second.cs() == "long") {
1501 third = p.get_token();
1503 while (p.good() && !p.isParagraph() &&
1504 (third.cat() == catSpace ||
1505 third.cat() == catNewline ||
1506 third.cat() == catComment)) {
1507 third = p.get_token();
1510 thirdvalid = third.cat() == catEscape;
1512 for (int i = 0; i < pos; ++i)
1517 return (first.cs() == "global" || first.cs() == "long") &&
1518 second.cs() == "def";
1519 return first.cs() == "global" && second.cs() == "long" &&
1520 third.cs() == "def";
1524 /// Parse a macro definition (assumes that is_macro() returned true)
1525 void parse_macro(Parser & p, ostream & os, Context & context)
1527 context.check_layout(os);
1528 Token first = p.curr_token();
1531 string command = first.asInput();
1532 if (first.cs() != "def") {
1534 eat_whitespace(p, os, context, false);
1535 second = p.curr_token();
1536 command += second.asInput();
1537 if (second.cs() != "def") {
1539 eat_whitespace(p, os, context, false);
1540 third = p.curr_token();
1541 command += third.asInput();
1544 eat_whitespace(p, os, context, false);
1545 string const name = p.get_token().cs();
1546 eat_whitespace(p, os, context, false);
1552 while (p.next_token().cat() != catBegin) {
1553 if (p.next_token().cat() == catParameter) {
1558 // followed by number?
1559 if (p.next_token().cat() == catOther) {
1560 char c = p.getChar();
1562 // number = current arity + 1?
1563 if (c == arity + '0' + 1)
1568 paramtext += p.get_token().cs();
1570 paramtext += p.get_token().cs();
1575 // only output simple (i.e. compatible) macro as FormulaMacros
1576 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1578 context.check_layout(os);
1579 begin_inset(os, "FormulaMacro");
1580 os << "\n\\def" << ert;
1583 handle_ert(os, command + ert, context);
1586 } // anonymous namespace
1589 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1592 Layout const * newlayout = 0;
1593 InsetLayout const * newinsetlayout = 0;
1594 // Store the latest bibliographystyle and nocite{*} option
1595 // (needed for bibtex inset)
1597 string bibliographystyle;
1598 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1599 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1602 Token const & t = p.get_token();
1605 debugToken(cerr, t, flags);
1608 if (flags & FLAG_ITEM) {
1609 if (t.cat() == catSpace)
1612 flags &= ~FLAG_ITEM;
1613 if (t.cat() == catBegin) {
1614 // skip the brace and collect everything to the next matching
1616 flags |= FLAG_BRACE_LAST;
1620 // handle only this single token, leave the loop if done
1621 flags |= FLAG_LEAVE;
1624 if (t.cat() != catEscape && t.character() == ']' &&
1625 (flags & FLAG_BRACK_LAST))
1627 if (t.cat() == catEnd && (flags & FLAG_BRACE_LAST))
1630 // If there is anything between \end{env} and \begin{env} we
1631 // don't need to output a separator.
1632 if (t.cat() != catSpace && t.cat() != catNewline &&
1633 t.asInput() != "\\begin")
1639 if (t.cat() == catMath) {
1640 // we are inside some text mode thingy, so opening new math is allowed
1641 context.check_layout(os);
1642 begin_inset(os, "Formula ");
1643 Token const & n = p.get_token();
1644 if (n.cat() == catMath && outer) {
1645 // TeX's $$...$$ syntax for displayed math
1647 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1649 p.get_token(); // skip the second '$' token
1651 // simple $...$ stuff
1654 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1660 else if (t.cat() == catSuper || t.cat() == catSub)
1661 cerr << "catcode " << t << " illegal in text mode\n";
1663 // Basic support for english quotes. This should be
1664 // extended to other quotes, but is not so easy (a
1665 // left english quote is the same as a right german
1667 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1668 context.check_layout(os);
1669 begin_inset(os, "Quotes ");
1675 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1676 context.check_layout(os);
1677 begin_inset(os, "Quotes ");
1684 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1685 context.check_layout(os);
1686 begin_inset(os, "Quotes ");
1693 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1694 context.check_layout(os);
1695 begin_inset(os, "Quotes ");
1702 else if (t.asInput() == "<"
1703 && p.next_token().asInput() == "<" && noweb_mode) {
1705 parse_noweb(p, os, context);
1708 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1709 check_space(p, os, context);
1711 else if (t.character() == '[' && noweb_mode &&
1712 p.next_token().character() == '[') {
1713 // These can contain underscores
1715 string const s = p.getFullOpt() + ']';
1716 if (p.next_token().character() == ']')
1719 cerr << "Warning: Inserting missing ']' in '"
1720 << s << "'." << endl;
1721 handle_ert(os, s, context);
1724 else if (t.cat() == catLetter) {
1725 context.check_layout(os);
1726 // Workaround for bug 4752.
1727 // FIXME: This whole code block needs to be removed
1728 // when the bug is fixed and tex2lyx produces
1729 // the updated file format.
1730 // The replacement algorithm in LyX is so stupid that
1731 // it even translates a phrase if it is part of a word.
1732 bool handled = false;
1733 for (int const * l = known_phrase_lengths; *l; ++l) {
1734 string phrase = t.cs();
1735 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1736 phrase += p.get_token().cs();
1737 if (is_known(phrase, known_coded_phrases)) {
1738 handle_ert(os, phrase, context);
1742 for (size_t i = 1; i < phrase.length(); ++i)
1750 else if (t.cat() == catOther ||
1751 t.cat() == catAlign ||
1752 t.cat() == catParameter) {
1753 // This translates "&" to "\\&" which may be wrong...
1754 context.check_layout(os);
1758 else if (p.isParagraph()) {
1759 if (context.new_layout_allowed)
1760 context.new_paragraph(os);
1762 handle_ert(os, "\\par ", context);
1763 eat_whitespace(p, os, context, true);
1766 else if (t.cat() == catActive) {
1767 context.check_layout(os);
1768 if (t.character() == '~') {
1769 if (context.layout->free_spacing)
1772 begin_inset(os, "space ~\n");
1779 else if (t.cat() == catBegin &&
1780 p.next_token().cat() == catEnd) {
1782 Token const prev = p.prev_token();
1784 if (p.next_token().character() == '`' ||
1785 (prev.character() == '-' &&
1786 p.next_token().character() == '-'))
1787 ; // ignore it in {}`` or -{}-
1789 handle_ert(os, "{}", context);
1793 else if (t.cat() == catBegin) {
1794 context.check_layout(os);
1795 // special handling of font attribute changes
1796 Token const prev = p.prev_token();
1797 Token const next = p.next_token();
1798 TeXFont const oldFont = context.font;
1799 if (next.character() == '[' ||
1800 next.character() == ']' ||
1801 next.character() == '*') {
1803 if (p.next_token().cat() == catEnd) {
1808 handle_ert(os, "{", context);
1809 parse_text_snippet(p, os,
1812 handle_ert(os, "}", context);
1814 } else if (! context.new_layout_allowed) {
1815 handle_ert(os, "{", context);
1816 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1818 handle_ert(os, "}", context);
1819 } else if (is_known(next.cs(), known_sizes)) {
1820 // next will change the size, so we must
1822 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1824 if (!context.atParagraphStart())
1826 << context.font.size << "\n";
1827 } else if (is_known(next.cs(), known_font_families)) {
1828 // next will change the font family, so we
1829 // must reset it here
1830 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1832 if (!context.atParagraphStart())
1834 << context.font.family << "\n";
1835 } else if (is_known(next.cs(), known_font_series)) {
1836 // next will change the font series, so we
1837 // must reset it here
1838 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1840 if (!context.atParagraphStart())
1842 << context.font.series << "\n";
1843 } else if (is_known(next.cs(), known_font_shapes)) {
1844 // next will change the font shape, so we
1845 // must reset it here
1846 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1848 if (!context.atParagraphStart())
1850 << context.font.shape << "\n";
1851 } else if (is_known(next.cs(), known_old_font_families) ||
1852 is_known(next.cs(), known_old_font_series) ||
1853 is_known(next.cs(), known_old_font_shapes)) {
1854 // next will change the font family, series
1855 // and shape, so we must reset it here
1856 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1858 if (!context.atParagraphStart())
1860 << context.font.family
1862 << context.font.series
1864 << context.font.shape << "\n";
1866 handle_ert(os, "{", context);
1867 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1869 handle_ert(os, "}", context);
1873 else if (t.cat() == catEnd) {
1874 if (flags & FLAG_BRACE_LAST) {
1877 cerr << "stray '}' in text\n";
1878 handle_ert(os, "}", context);
1881 else if (t.cat() == catComment)
1882 parse_comment(p, os, t, context);
1885 // control sequences
1888 else if (t.cs() == "(") {
1889 context.check_layout(os);
1890 begin_inset(os, "Formula");
1892 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1897 else if (t.cs() == "[") {
1898 context.check_layout(os);
1899 begin_inset(os, "Formula");
1901 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1906 else if (t.cs() == "begin")
1907 parse_environment(p, os, outer, last_env, context);
1909 else if (t.cs() == "end") {
1910 if (flags & FLAG_END) {
1911 // eat environment name
1912 string const name = p.getArg('{', '}');
1913 if (name != active_environment())
1914 cerr << "\\end{" + name + "} does not match \\begin{"
1915 + active_environment() + "}\n";
1918 p.error("found 'end' unexpectedly");
1921 else if (t.cs() == "item") {
1924 bool optarg = false;
1925 if (p.next_token().cat() != catEscape &&
1926 p.next_token().character() == '[') {
1927 p.get_token(); // eat '['
1928 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1933 context.check_layout(os);
1934 if (context.has_item) {
1935 // An item in an unknown list-like environment
1936 // FIXME: Do this in check_layout()!
1937 context.has_item = false;
1939 handle_ert(os, "\\item", context);
1941 handle_ert(os, "\\item ", context);
1944 if (context.layout->labeltype != LABEL_MANUAL) {
1945 // LyX does not support \item[\mybullet]
1946 // in itemize environments
1947 handle_ert(os, "[", context);
1949 handle_ert(os, "]", context);
1950 } else if (!s.empty()) {
1951 // The space is needed to separate the
1952 // item from the rest of the sentence.
1954 eat_whitespace(p, os, context, false);
1959 else if (t.cs() == "bibitem") {
1961 context.check_layout(os);
1962 string label = convert_command_inset_arg(p.getArg('[', ']'));
1963 string key = convert_command_inset_arg(p.verbatim_item());
1964 if (contains(label, '\\') || contains(key, '\\')) {
1965 // LyX can't handle LaTeX commands in labels or keys
1966 handle_ert(os, t.asInput() + '[' + label +
1967 "]{" + p.verbatim_item() + '}',
1970 begin_command_inset(os, "bibitem", "bibitem");
1971 os << "label \"" << label << "\"\n"
1972 "key \"" << key << "\"\n";
1977 else if (is_macro(p))
1978 parse_macro(p, os, context);
1980 else if (t.cs() == "noindent") {
1982 context.add_par_extra_stuff("\\noindent\n");
1985 else if (t.cs() == "appendix") {
1986 context.add_par_extra_stuff("\\start_of_appendix\n");
1987 // We need to start a new paragraph. Otherwise the
1988 // appendix in 'bla\appendix\chapter{' would start
1990 context.new_paragraph(os);
1991 // We need to make sure that the paragraph is
1992 // generated even if it is empty. Otherwise the
1993 // appendix in '\par\appendix\par\chapter{' would
1995 context.check_layout(os);
1996 // FIXME: This is a hack to prevent paragraph
1997 // deletion if it is empty. Handle this better!
1999 "%dummy comment inserted by tex2lyx to "
2000 "ensure that this paragraph is not empty",
2002 // Both measures above may generate an additional
2003 // empty paragraph, but that does not hurt, because
2004 // whitespace does not matter here.
2005 eat_whitespace(p, os, context, true);
2008 // Starred section headings
2009 // Must attempt to parse "Section*" before "Section".
2010 else if ((p.next_token().asInput() == "*") &&
2011 context.new_layout_allowed &&
2012 (newlayout = findLayout(context.textclass, t.cs() + '*', true))) {
2015 output_command_layout(os, p, outer, context, newlayout);
2019 // Section headings and the like
2020 else if (context.new_layout_allowed &&
2021 (newlayout = findLayout(context.textclass, t.cs(), true))) {
2023 output_command_layout(os, p, outer, context, newlayout);
2027 else if (t.cs() == "caption") {
2029 context.check_layout(os);
2031 begin_inset(os, "Caption\n\n");
2032 Context newcontext(true, context.textclass);
2033 newcontext.font = context.font;
2034 newcontext.check_layout(os);
2035 if (p.next_token().cat() != catEscape &&
2036 p.next_token().character() == '[') {
2037 p.get_token(); // eat '['
2038 begin_inset(os, "OptArg\n");
2039 os << "status collapsed\n";
2040 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
2042 eat_whitespace(p, os, context, false);
2044 parse_text(p, os, FLAG_ITEM, outer, context);
2045 context.check_end_layout(os);
2046 // We don't need really a new paragraph, but
2047 // we must make sure that the next item gets a \begin_layout.
2048 context.new_paragraph(os);
2051 newcontext.check_end_layout(os);
2054 else if (t.cs() == "includegraphics") {
2055 bool const clip = p.next_token().asInput() == "*";
2058 string const arg = p.getArg('[', ']');
2059 map<string, string> opts;
2060 vector<string> keys;
2061 split_map(arg, opts, keys);
2063 opts["clip"] = string();
2064 string name = normalize_filename(p.verbatim_item());
2066 string const path = getMasterFilePath();
2067 // We want to preserve relative / absolute filenames,
2068 // therefore path is only used for testing
2069 if (!makeAbsPath(name, path).exists()) {
2070 // The file extension is probably missing.
2071 // Now try to find it out.
2072 string const dvips_name =
2073 find_file(name, path,
2074 known_dvips_graphics_formats);
2075 string const pdftex_name =
2076 find_file(name, path,
2077 known_pdftex_graphics_formats);
2078 if (!dvips_name.empty()) {
2079 if (!pdftex_name.empty()) {
2080 cerr << "This file contains the "
2082 "\"\\includegraphics{"
2084 "However, files\n\""
2085 << dvips_name << "\" and\n\""
2086 << pdftex_name << "\"\n"
2087 "both exist, so I had to make a "
2088 "choice and took the first one.\n"
2089 "Please move the unwanted one "
2090 "someplace else and try again\n"
2091 "if my choice was wrong."
2095 } else if (!pdftex_name.empty()) {
2101 if (makeAbsPath(name, path).exists())
2102 fix_relative_filename(name);
2104 cerr << "Warning: Could not find graphics file '"
2105 << name << "'." << endl;
2107 context.check_layout(os);
2108 begin_inset(os, "Graphics ");
2109 os << "\n\tfilename " << name << '\n';
2110 if (opts.find("width") != opts.end())
2112 << translate_len(opts["width"]) << '\n';
2113 if (opts.find("height") != opts.end())
2115 << translate_len(opts["height"]) << '\n';
2116 if (opts.find("scale") != opts.end()) {
2117 istringstream iss(opts["scale"]);
2121 os << "\tscale " << val << '\n';
2123 if (opts.find("angle") != opts.end()) {
2124 os << "\trotateAngle "
2125 << opts["angle"] << '\n';
2126 vector<string>::const_iterator a =
2127 find(keys.begin(), keys.end(), "angle");
2128 vector<string>::const_iterator s =
2129 find(keys.begin(), keys.end(), "width");
2130 if (s == keys.end())
2131 s = find(keys.begin(), keys.end(), "height");
2132 if (s == keys.end())
2133 s = find(keys.begin(), keys.end(), "scale");
2134 if (s != keys.end() && distance(s, a) > 0)
2135 os << "\tscaleBeforeRotation\n";
2137 if (opts.find("origin") != opts.end()) {
2139 string const opt = opts["origin"];
2140 if (opt.find('l') != string::npos) ss << "left";
2141 if (opt.find('r') != string::npos) ss << "right";
2142 if (opt.find('c') != string::npos) ss << "center";
2143 if (opt.find('t') != string::npos) ss << "Top";
2144 if (opt.find('b') != string::npos) ss << "Bottom";
2145 if (opt.find('B') != string::npos) ss << "Baseline";
2146 if (!ss.str().empty())
2147 os << "\trotateOrigin " << ss.str() << '\n';
2149 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
2151 if (opts.find("keepaspectratio") != opts.end())
2152 os << "\tkeepAspectRatio\n";
2153 if (opts.find("clip") != opts.end())
2155 if (opts.find("draft") != opts.end())
2157 if (opts.find("bb") != opts.end())
2158 os << "\tBoundingBox "
2159 << opts["bb"] << '\n';
2160 int numberOfbbOptions = 0;
2161 if (opts.find("bbllx") != opts.end())
2162 numberOfbbOptions++;
2163 if (opts.find("bblly") != opts.end())
2164 numberOfbbOptions++;
2165 if (opts.find("bburx") != opts.end())
2166 numberOfbbOptions++;
2167 if (opts.find("bbury") != opts.end())
2168 numberOfbbOptions++;
2169 if (numberOfbbOptions == 4)
2170 os << "\tBoundingBox "
2171 << opts["bbllx"] << " " << opts["bblly"] << " "
2172 << opts["bburx"] << " " << opts["bbury"] << '\n';
2173 else if (numberOfbbOptions > 0)
2174 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2175 numberOfbbOptions = 0;
2176 if (opts.find("natwidth") != opts.end())
2177 numberOfbbOptions++;
2178 if (opts.find("natheight") != opts.end())
2179 numberOfbbOptions++;
2180 if (numberOfbbOptions == 2)
2181 os << "\tBoundingBox 0bp 0bp "
2182 << opts["natwidth"] << " " << opts["natheight"] << '\n';
2183 else if (numberOfbbOptions > 0)
2184 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
2185 ostringstream special;
2186 if (opts.find("hiresbb") != opts.end())
2187 special << "hiresbb,";
2188 if (opts.find("trim") != opts.end())
2190 if (opts.find("viewport") != opts.end())
2191 special << "viewport=" << opts["viewport"] << ',';
2192 if (opts.find("totalheight") != opts.end())
2193 special << "totalheight=" << opts["totalheight"] << ',';
2194 if (opts.find("type") != opts.end())
2195 special << "type=" << opts["type"] << ',';
2196 if (opts.find("ext") != opts.end())
2197 special << "ext=" << opts["ext"] << ',';
2198 if (opts.find("read") != opts.end())
2199 special << "read=" << opts["read"] << ',';
2200 if (opts.find("command") != opts.end())
2201 special << "command=" << opts["command"] << ',';
2202 string s_special = special.str();
2203 if (!s_special.empty()) {
2204 // We had special arguments. Remove the trailing ','.
2205 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
2207 // TODO: Handle the unknown settings better.
2208 // Warn about invalid options.
2209 // Check whether some option was given twice.
2213 else if (t.cs() == "footnote" ||
2214 (t.cs() == "thanks" && context.layout->intitle)) {
2216 context.check_layout(os);
2217 begin_inset(os, "Foot\n");
2218 os << "status collapsed\n\n";
2219 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2223 else if (t.cs() == "marginpar") {
2225 context.check_layout(os);
2226 begin_inset(os, "Marginal\n");
2227 os << "status collapsed\n\n";
2228 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2232 else if (t.cs() == "ensuremath") {
2234 context.check_layout(os);
2235 string const s = p.verbatim_item();
2236 //FIXME: this never triggers in UTF8
2237 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
2240 handle_ert(os, "\\ensuremath{" + s + "}",
2244 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
2245 // FIXME: Somehow prevent title layouts if
2246 // "maketitle" was not found
2248 skip_spaces_braces(p);
2251 else if (t.cs() == "tableofcontents") {
2252 context.check_layout(os);
2253 begin_command_inset(os, "toc", "tableofcontents");
2255 skip_spaces_braces(p);
2258 else if (t.cs() == "listoffigures") {
2259 context.check_layout(os);
2260 begin_inset(os, "FloatList figure\n");
2262 skip_spaces_braces(p);
2265 else if (t.cs() == "listoftables") {
2266 context.check_layout(os);
2267 begin_inset(os, "FloatList table\n");
2269 skip_spaces_braces(p);
2272 else if (t.cs() == "listof") {
2273 p.skip_spaces(true);
2274 string const name = p.get_token().cs();
2275 if (context.textclass.floats().typeExist(name)) {
2276 context.check_layout(os);
2277 begin_inset(os, "FloatList ");
2280 p.get_token(); // swallow second arg
2282 handle_ert(os, "\\listof{" + name + "}", context);
2285 else if (t.cs() == "textrm")
2286 parse_text_attributes(p, os, FLAG_ITEM, outer,
2287 context, "\\family",
2288 context.font.family, "roman");
2290 else if (t.cs() == "textsf")
2291 parse_text_attributes(p, os, FLAG_ITEM, outer,
2292 context, "\\family",
2293 context.font.family, "sans");
2295 else if (t.cs() == "texttt")
2296 parse_text_attributes(p, os, FLAG_ITEM, outer,
2297 context, "\\family",
2298 context.font.family, "typewriter");
2300 else if (t.cs() == "textmd")
2301 parse_text_attributes(p, os, FLAG_ITEM, outer,
2302 context, "\\series",
2303 context.font.series, "medium");
2305 else if (t.cs() == "textbf")
2306 parse_text_attributes(p, os, FLAG_ITEM, outer,
2307 context, "\\series",
2308 context.font.series, "bold");
2310 else if (t.cs() == "textup")
2311 parse_text_attributes(p, os, FLAG_ITEM, outer,
2313 context.font.shape, "up");
2315 else if (t.cs() == "textit")
2316 parse_text_attributes(p, os, FLAG_ITEM, outer,
2318 context.font.shape, "italic");
2320 else if (t.cs() == "textsl")
2321 parse_text_attributes(p, os, FLAG_ITEM, outer,
2323 context.font.shape, "slanted");
2325 else if (t.cs() == "textsc")
2326 parse_text_attributes(p, os, FLAG_ITEM, outer,
2328 context.font.shape, "smallcaps");
2330 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2331 context.check_layout(os);
2332 TeXFont oldFont = context.font;
2333 context.font.init();
2334 context.font.size = oldFont.size;
2335 os << "\n\\family " << context.font.family << "\n";
2336 os << "\n\\series " << context.font.series << "\n";
2337 os << "\n\\shape " << context.font.shape << "\n";
2338 if (t.cs() == "textnormal") {
2339 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2340 output_font_change(os, context.font, oldFont);
2341 context.font = oldFont;
2343 eat_whitespace(p, os, context, false);
2346 else if (t.cs() == "textcolor") {
2347 // scheme is \textcolor{color name}{text}
2348 string const color = p.verbatim_item();
2349 // we only support the predefined colors of the color package
2350 if (color == "black" || color == "blue" || color == "cyan"
2351 || color == "green" || color == "magenta" || color == "red"
2352 || color == "white" || color == "yellow") {
2353 context.check_layout(os);
2354 os << "\n\\color " << color << "\n";
2355 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2356 context.check_layout(os);
2357 os << "\n\\color inherit\n";
2359 // for custom defined colors
2360 handle_ert(os, t.asInput() + "{" + color + "}", context);
2363 else if (t.cs() == "underbar") {
2364 // Do NOT handle \underline.
2365 // \underbar cuts through y, g, q, p etc.,
2366 // \underline does not.
2367 context.check_layout(os);
2368 os << "\n\\bar under\n";
2369 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2370 context.check_layout(os);
2371 os << "\n\\bar default\n";
2374 else if (t.cs() == "emph" || t.cs() == "noun") {
2375 context.check_layout(os);
2376 os << "\n\\" << t.cs() << " on\n";
2377 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2378 context.check_layout(os);
2379 os << "\n\\" << t.cs() << " default\n";
2382 else if (t.cs() == "lyxline") {
2383 context.check_layout(os);
2387 else if (is_known(t.cs(), known_phrases) ||
2388 (t.cs() == "protect" &&
2389 p.next_token().cat() == catEscape &&
2390 is_known(p.next_token().cs(), known_phrases))) {
2391 // LyX sometimes puts a \protect in front, so we have to ignore it
2392 // FIXME: This needs to be changed when bug 4752 is fixed.
2393 char const * const * where = is_known(
2394 t.cs() == "protect" ? p.get_token().cs() : t.cs(),
2396 context.check_layout(os);
2397 os << known_coded_phrases[where - known_phrases];
2398 skip_spaces_braces(p);
2401 else if (is_known(t.cs(), known_ref_commands)) {
2402 string const opt = p.getOpt();
2404 context.check_layout(os);
2405 begin_command_inset(os, "ref", t.cs());
2406 os << "reference \""
2407 << convert_command_inset_arg(p.verbatim_item())
2411 // LyX does not support optional arguments of ref commands
2412 handle_ert(os, t.asInput() + '[' + opt + "]{" +
2413 p.verbatim_item() + "}", context);
2417 else if (use_natbib &&
2418 is_known(t.cs(), known_natbib_commands) &&
2419 ((t.cs() != "citefullauthor" &&
2420 t.cs() != "citeyear" &&
2421 t.cs() != "citeyearpar") ||
2422 p.next_token().asInput() != "*")) {
2423 context.check_layout(os);
2424 string command = t.cs();
2425 if (p.next_token().asInput() == "*") {
2429 if (command == "citefullauthor")
2430 // alternative name for "\\citeauthor*"
2431 command = "citeauthor*";
2433 // text before the citation
2435 // text after the citation
2437 get_cite_arguments(p, true, before, after);
2439 if (command == "cite") {
2440 // \cite without optional argument means
2441 // \citet, \cite with at least one optional
2442 // argument means \citep.
2443 if (before.empty() && after.empty())
2448 if (before.empty() && after == "[]")
2449 // avoid \citet[]{a}
2451 else if (before == "[]" && after == "[]") {
2452 // avoid \citet[][]{a}
2456 // remove the brackets around after and before
2457 if (!after.empty()) {
2459 after.erase(after.length() - 1, 1);
2460 after = convert_command_inset_arg(after);
2462 if (!before.empty()) {
2464 before.erase(before.length() - 1, 1);
2465 before = convert_command_inset_arg(before);
2467 begin_command_inset(os, "citation", command);
2468 os << "after " << '"' << after << '"' << "\n";
2469 os << "before " << '"' << before << '"' << "\n";
2471 << convert_command_inset_arg(p.verbatim_item())
2476 else if (use_jurabib &&
2477 is_known(t.cs(), known_jurabib_commands) &&
2478 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2479 context.check_layout(os);
2480 string command = t.cs();
2481 if (p.next_token().asInput() == "*") {
2485 char argumentOrder = '\0';
2486 vector<string> const & options = used_packages["jurabib"];
2487 if (find(options.begin(), options.end(),
2488 "natbiborder") != options.end())
2489 argumentOrder = 'n';
2490 else if (find(options.begin(), options.end(),
2491 "jurabiborder") != options.end())
2492 argumentOrder = 'j';
2494 // text before the citation
2496 // text after the citation
2498 get_cite_arguments(p, argumentOrder != 'j', before, after);
2500 string const citation = p.verbatim_item();
2501 if (!before.empty() && argumentOrder == '\0') {
2502 cerr << "Warning: Assuming argument order "
2503 "of jurabib version 0.6 for\n'"
2504 << command << before << after << '{'
2505 << citation << "}'.\n"
2506 "Add 'jurabiborder' to the jurabib "
2507 "package options if you used an\n"
2508 "earlier jurabib version." << endl;
2510 if (!after.empty()) {
2512 after.erase(after.length() - 1, 1);
2514 if (!before.empty()) {
2516 before.erase(before.length() - 1, 1);
2518 begin_command_inset(os, "citation", command);
2519 os << "after " << '"' << after << '"' << "\n";
2520 os << "before " << '"' << before << '"' << "\n";
2521 os << "key " << '"' << citation << '"' << "\n";
2525 else if (t.cs() == "cite"
2526 || t.cs() == "nocite") {
2527 context.check_layout(os);
2528 string after = convert_command_inset_arg(p.getArg('[', ']'));
2529 string key = convert_command_inset_arg(p.verbatim_item());
2530 // store the case that it is "\nocite{*}" to use it later for
2533 begin_command_inset(os, "citation", t.cs());
2534 os << "after " << '"' << after << '"' << "\n";
2535 os << "key " << '"' << key << '"' << "\n";
2537 } else if (t.cs() == "nocite")
2541 else if (t.cs() == "index") {
2542 context.check_layout(os);
2543 begin_inset(os, "Index\n");
2544 os << "status collapsed\n";
2545 parse_text_in_inset(p, os, FLAG_ITEM, false, context, "Index");
2549 else if (t.cs() == "nomenclature") {
2550 context.check_layout(os);
2551 begin_command_inset(os, "nomenclature", "nomenclature");
2552 string prefix = convert_command_inset_arg(p.getArg('[', ']'));
2553 if (!prefix.empty())
2554 os << "prefix " << '"' << prefix << '"' << "\n";
2555 os << "symbol " << '"'
2556 << convert_command_inset_arg(p.verbatim_item());
2557 os << "\"\ndescription \""
2558 << convert_command_inset_arg(p.verbatim_item())
2563 else if (t.cs() == "label") {
2564 context.check_layout(os);
2565 begin_command_inset(os, "label", "label");
2567 << convert_command_inset_arg(p.verbatim_item())
2572 else if (t.cs() == "printindex") {
2573 context.check_layout(os);
2574 begin_command_inset(os, "index_print", "printindex");
2576 skip_spaces_braces(p);
2579 else if (t.cs() == "printnomenclature") {
2580 context.check_layout(os);
2581 begin_command_inset(os, "nomencl_print", "printnomenclature");
2583 skip_spaces_braces(p);
2586 else if (LYX_FORMAT >= 408 &&
2587 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2588 context.check_layout(os);
2589 begin_inset(os, "script ");
2590 os << t.cs().substr(4) << '\n';
2591 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2595 else if (is_known(t.cs(), known_quotes)) {
2596 char const * const * where = is_known(t.cs(), known_quotes);
2597 context.check_layout(os);
2598 begin_inset(os, "Quotes ");
2599 os << known_coded_quotes[where - known_quotes];
2601 // LyX adds {} after the quote, so we have to eat
2602 // spaces here if there are any before a possible
2604 eat_whitespace(p, os, context, false);
2608 else if (is_known(t.cs(), known_sizes) &&
2609 context.new_layout_allowed) {
2610 char const * const * where = is_known(t.cs(), known_sizes);
2611 context.check_layout(os);
2612 TeXFont const oldFont = context.font;
2613 context.font.size = known_coded_sizes[where - known_sizes];
2614 output_font_change(os, oldFont, context.font);
2615 eat_whitespace(p, os, context, false);
2618 else if (is_known(t.cs(), known_font_families) &&
2619 context.new_layout_allowed) {
2620 char const * const * where =
2621 is_known(t.cs(), known_font_families);
2622 context.check_layout(os);
2623 TeXFont const oldFont = context.font;
2624 context.font.family =
2625 known_coded_font_families[where - known_font_families];
2626 output_font_change(os, oldFont, context.font);
2627 eat_whitespace(p, os, context, false);
2630 else if (is_known(t.cs(), known_font_series) &&
2631 context.new_layout_allowed) {
2632 char const * const * where =
2633 is_known(t.cs(), known_font_series);
2634 context.check_layout(os);
2635 TeXFont const oldFont = context.font;
2636 context.font.series =
2637 known_coded_font_series[where - known_font_series];
2638 output_font_change(os, oldFont, context.font);
2639 eat_whitespace(p, os, context, false);
2642 else if (is_known(t.cs(), known_font_shapes) &&
2643 context.new_layout_allowed) {
2644 char const * const * where =
2645 is_known(t.cs(), known_font_shapes);
2646 context.check_layout(os);
2647 TeXFont const oldFont = context.font;
2648 context.font.shape =
2649 known_coded_font_shapes[where - known_font_shapes];
2650 output_font_change(os, oldFont, context.font);
2651 eat_whitespace(p, os, context, false);
2653 else if (is_known(t.cs(), known_old_font_families) &&
2654 context.new_layout_allowed) {
2655 char const * const * where =
2656 is_known(t.cs(), known_old_font_families);
2657 context.check_layout(os);
2658 TeXFont const oldFont = context.font;
2659 context.font.init();
2660 context.font.size = oldFont.size;
2661 context.font.family =
2662 known_coded_font_families[where - known_old_font_families];
2663 output_font_change(os, oldFont, context.font);
2664 eat_whitespace(p, os, context, false);
2667 else if (is_known(t.cs(), known_old_font_series) &&
2668 context.new_layout_allowed) {
2669 char const * const * where =
2670 is_known(t.cs(), known_old_font_series);
2671 context.check_layout(os);
2672 TeXFont const oldFont = context.font;
2673 context.font.init();
2674 context.font.size = oldFont.size;
2675 context.font.series =
2676 known_coded_font_series[where - known_old_font_series];
2677 output_font_change(os, oldFont, context.font);
2678 eat_whitespace(p, os, context, false);
2681 else if (is_known(t.cs(), known_old_font_shapes) &&
2682 context.new_layout_allowed) {
2683 char const * const * where =
2684 is_known(t.cs(), known_old_font_shapes);
2685 context.check_layout(os);
2686 TeXFont const oldFont = context.font;
2687 context.font.init();
2688 context.font.size = oldFont.size;
2689 context.font.shape =
2690 known_coded_font_shapes[where - known_old_font_shapes];
2691 output_font_change(os, oldFont, context.font);
2692 eat_whitespace(p, os, context, false);
2695 else if (t.cs() == "selectlanguage") {
2696 context.check_layout(os);
2697 // save the language for the case that a
2698 // \foreignlanguage is used
2700 context.font.language = babel2lyx(p.verbatim_item());
2701 os << "\n\\lang " << context.font.language << "\n";
2704 else if (t.cs() == "foreignlanguage") {
2705 string const lang = babel2lyx(p.verbatim_item());
2706 parse_text_attributes(p, os, FLAG_ITEM, outer,
2708 context.font.language, lang);
2711 else if (t.cs() == "inputencoding") {
2712 // nothing to write here
2713 string const enc = subst(p.verbatim_item(), "\n", " ");
2717 else if (t.cs() == "ldots") {
2718 context.check_layout(os);
2719 os << "\\SpecialChar \\ldots{}\n";
2720 skip_spaces_braces(p);
2723 else if (t.cs() == "lyxarrow") {
2724 context.check_layout(os);
2725 os << "\\SpecialChar \\menuseparator\n";
2726 skip_spaces_braces(p);
2729 else if (t.cs() == "textcompwordmark") {
2730 context.check_layout(os);
2731 os << "\\SpecialChar \\textcompwordmark{}\n";
2732 skip_spaces_braces(p);
2735 else if (t.cs() == "slash") {
2736 context.check_layout(os);
2737 os << "\\SpecialChar \\slash{}\n";
2738 skip_spaces_braces(p);
2741 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2742 context.check_layout(os);
2743 os << "\\SpecialChar \\nobreakdash-\n";
2747 else if (t.cs() == "textquotedbl") {
2748 context.check_layout(os);
2753 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2754 context.check_layout(os);
2755 os << "\\SpecialChar \\@.\n";
2759 else if (t.cs() == "-") {
2760 context.check_layout(os);
2761 os << "\\SpecialChar \\-\n";
2764 else if (t.cs() == "textasciitilde") {
2765 context.check_layout(os);
2767 skip_spaces_braces(p);
2770 else if (t.cs() == "textasciicircum") {
2771 context.check_layout(os);
2773 skip_spaces_braces(p);
2776 else if (t.cs() == "textbackslash") {
2777 context.check_layout(os);
2778 os << "\n\\backslash\n";
2779 skip_spaces_braces(p);
2782 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2783 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2785 context.check_layout(os);
2789 else if (t.cs() == "char") {
2790 context.check_layout(os);
2791 if (p.next_token().character() == '`') {
2793 if (p.next_token().cs() == "\"") {
2798 handle_ert(os, "\\char`", context);
2801 handle_ert(os, "\\char", context);
2805 else if (t.cs() == "verb") {
2806 context.check_layout(os);
2807 char const delimiter = p.next_token().character();
2808 string const arg = p.getArg(delimiter, delimiter);
2810 oss << "\\verb" << delimiter << arg << delimiter;
2811 handle_ert(os, oss.str(), context);
2814 // Problem: \= creates a tabstop inside the tabbing environment
2815 // and else an accent. In the latter case we really would want
2816 // \={o} instead of \= o.
2817 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2818 handle_ert(os, t.asInput(), context);
2820 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2821 else if (t.cs().size() == 1
2822 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2823 context.check_layout(os);
2824 // try to see whether the string is in unicodesymbols
2826 string command = t.asInput() + "{"
2827 + trim(p.verbatim_item())
2829 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2832 cerr << "When parsing " << command
2833 << ", result is " << to_utf8(s)
2834 << "+" << to_utf8(rem) << endl;
2837 // we did not find a non-ert version
2838 handle_ert(os, command, context);
2841 else if (t.cs() == "\\") {
2842 context.check_layout(os);
2844 handle_ert(os, "\\\\" + p.getOpt(), context);
2845 else if (p.next_token().asInput() == "*") {
2847 // getOpt() eats the following space if there
2848 // is no optional argument, but that is OK
2849 // here since it has no effect in the output.
2850 handle_ert(os, "\\\\*" + p.getOpt(), context);
2853 begin_inset(os, "Newline newline");
2858 else if (t.cs() == "newline" ||
2859 (t.cs() == "linebreak" && !p.hasOpt())) {
2860 context.check_layout(os);
2861 begin_inset(os, "Newline ");
2864 skip_spaces_braces(p);
2867 else if (t.cs() == "input" || t.cs() == "include"
2868 || t.cs() == "verbatiminput") {
2869 string name = t.cs();
2870 if (t.cs() == "verbatiminput"
2871 && p.next_token().asInput() == "*")
2872 name += p.get_token().asInput();
2873 context.check_layout(os);
2874 string filename(normalize_filename(p.getArg('{', '}')));
2875 string const path = getMasterFilePath();
2876 // We want to preserve relative / absolute filenames,
2877 // therefore path is only used for testing
2878 if ((t.cs() == "include" || t.cs() == "input") &&
2879 !makeAbsPath(filename, path).exists()) {
2880 // The file extension is probably missing.
2881 // Now try to find it out.
2882 string const tex_name =
2883 find_file(filename, path,
2884 known_tex_extensions);
2885 if (!tex_name.empty())
2886 filename = tex_name;
2888 bool external = false;
2890 if (makeAbsPath(filename, path).exists()) {
2891 string const abstexname =
2892 makeAbsPath(filename, path).absFileName();
2893 string const abslyxname =
2894 changeExtension(abstexname, ".lyx");
2895 string const absfigname =
2896 changeExtension(abstexname, ".fig");
2897 fix_relative_filename(filename);
2898 string const lyxname =
2899 changeExtension(filename, ".lyx");
2901 external = FileName(absfigname).exists();
2902 if (t.cs() == "input") {
2903 string const ext = getExtension(abstexname);
2905 // Combined PS/LaTeX:
2906 // x.eps, x.pstex_t (old xfig)
2907 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2908 FileName const absepsname(
2909 changeExtension(abstexname, ".eps"));
2910 FileName const abspstexname(
2911 changeExtension(abstexname, ".pstex"));
2912 bool const xfigeps =
2913 (absepsname.exists() ||
2914 abspstexname.exists()) &&
2917 // Combined PDF/LaTeX:
2918 // x.pdf, x.pdftex_t (old xfig)
2919 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2920 FileName const abspdfname(
2921 changeExtension(abstexname, ".pdf"));
2922 bool const xfigpdf =
2923 abspdfname.exists() &&
2924 (ext == "pdftex_t" || ext == "pdf_t");
2928 // Combined PS/PDF/LaTeX:
2929 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2930 string const absbase2(
2931 removeExtension(abstexname) + "_pspdftex");
2932 FileName const abseps2name(
2933 addExtension(absbase2, ".eps"));
2934 FileName const abspdf2name(
2935 addExtension(absbase2, ".pdf"));
2936 bool const xfigboth =
2937 abspdf2name.exists() &&
2938 abseps2name.exists() && ext == "pspdftex";
2940 xfig = xfigpdf || xfigeps || xfigboth;
2941 external = external && xfig;
2944 outname = changeExtension(filename, ".fig");
2946 // Don't try to convert, the result
2947 // would be full of ERT.
2949 } else if (t.cs() != "verbatiminput" &&
2950 tex2lyx(abstexname, FileName(abslyxname),
2957 cerr << "Warning: Could not find included file '"
2958 << filename << "'." << endl;
2962 begin_inset(os, "External\n");
2963 os << "\ttemplate XFig\n"
2964 << "\tfilename " << outname << '\n';
2966 begin_command_inset(os, "include", name);
2967 os << "preview false\n"
2968 "filename \"" << outname << "\"\n";
2973 else if (t.cs() == "bibliographystyle") {
2974 // store new bibliographystyle
2975 bibliographystyle = p.verbatim_item();
2976 // If any other command than \bibliography and
2977 // \nocite{*} follows, we need to output the style
2978 // (because it might be used by that command).
2979 // Otherwise, it will automatically be output by LyX.
2982 for (Token t2 = p.get_token(); p.good(); t2 = p.get_token()) {
2983 if (t2.cat() == catBegin)
2985 if (t2.cat() != catEscape)
2987 if (t2.cs() == "nocite") {
2988 if (p.getArg('{', '}') == "*")
2990 } else if (t2.cs() == "bibliography")
2997 "\\bibliographystyle{" + bibliographystyle + '}',
3002 else if (t.cs() == "bibliography") {
3003 context.check_layout(os);
3004 begin_command_inset(os, "bibtex", "bibtex");
3005 if (!btprint.empty()) {
3006 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
3007 // clear the string because the next BibTeX inset can be without the
3008 // \nocite{*} option
3011 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
3012 // Do we have a bibliographystyle set?
3013 if (!bibliographystyle.empty())
3014 os << "options " << '"' << bibliographystyle << '"' << "\n";
3018 else if (t.cs() == "parbox")
3019 parse_box(p, os, 0, FLAG_ITEM, outer, context, "", "", t.cs());
3021 else if (t.cs() == "ovalbox" || t.cs() == "Ovalbox" ||
3022 t.cs() == "shadowbox" || t.cs() == "doublebox")
3023 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), "");
3025 else if (t.cs() == "framebox") {
3026 string special = p.getFullOpt();
3027 special += p.getOpt();
3028 parse_outer_box(p, os, FLAG_ITEM, outer, context, t.cs(), special);
3031 //\makebox() is part of the picture environment and different from \makebox{}
3032 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
3033 else if (t.cs() == "makebox") {
3034 string arg = t.asInput();
3035 if (p.next_token().character() == '(')
3036 //the syntax is: \makebox(x,y)[position]{content}
3037 arg += p.getFullParentheseArg();
3039 //the syntax is: \makebox[width][position]{content}
3040 arg += p.getFullOpt();
3041 handle_ert(os, arg + p.getFullOpt(), context);
3044 else if (t.cs() == "smallskip" ||
3045 t.cs() == "medskip" ||
3046 t.cs() == "bigskip" ||
3047 t.cs() == "vfill") {
3048 context.check_layout(os);
3049 begin_inset(os, "VSpace ");
3052 skip_spaces_braces(p);
3055 else if (is_known(t.cs(), known_spaces)) {
3056 char const * const * where = is_known(t.cs(), known_spaces);
3057 context.check_layout(os);
3058 begin_inset(os, "space ");
3059 os << '\\' << known_coded_spaces[where - known_spaces]
3062 // LaTeX swallows whitespace after all spaces except
3063 // "\\,". We have to do that here, too, because LyX
3064 // adds "{}" which would make the spaces significant.
3066 eat_whitespace(p, os, context, false);
3067 // LyX adds "{}" after all spaces except "\\ " and
3068 // "\\,", so we have to remove "{}".
3069 // "\\,{}" is equivalent to "\\," in LaTeX, so we
3070 // remove the braces after "\\,", too.
3075 else if (t.cs() == "newpage" ||
3076 (t.cs() == "pagebreak" && !p.hasOpt()) ||
3077 t.cs() == "clearpage" ||
3078 t.cs() == "cleardoublepage") {
3079 context.check_layout(os);
3080 begin_inset(os, "Newpage ");
3083 skip_spaces_braces(p);
3086 else if (t.cs() == "DeclareRobustCommand" ||
3087 t.cs() == "DeclareRobustCommandx" ||
3088 t.cs() == "newcommand" ||
3089 t.cs() == "newcommandx" ||
3090 t.cs() == "providecommand" ||
3091 t.cs() == "providecommandx" ||
3092 t.cs() == "renewcommand" ||
3093 t.cs() == "renewcommandx") {
3094 // DeclareRobustCommand, DeclareRobustCommandx,
3095 // providecommand and providecommandx could be handled
3096 // by parse_command(), but we need to call
3097 // add_known_command() here.
3098 string name = t.asInput();
3099 if (p.next_token().asInput() == "*") {
3100 // Starred form. Eat '*'
3104 string const command = p.verbatim_item();
3105 string const opt1 = p.getFullOpt();
3106 string const opt2 = p.getFullOpt();
3107 add_known_command(command, opt1, !opt2.empty());
3108 string const ert = name + '{' + command + '}' +
3110 '{' + p.verbatim_item() + '}';
3112 if (t.cs() == "DeclareRobustCommand" ||
3113 t.cs() == "DeclareRobustCommandx" ||
3114 t.cs() == "providecommand" ||
3115 t.cs() == "providecommandx" ||
3116 name[name.length()-1] == '*')
3117 handle_ert(os, ert, context);
3119 context.check_layout(os);
3120 begin_inset(os, "FormulaMacro");
3126 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
3127 // let could be handled by parse_command(),
3128 // but we need to call add_known_command() here.
3129 string ert = t.asInput();
3132 if (p.next_token().cat() == catBegin) {
3133 name = p.verbatim_item();
3134 ert += '{' + name + '}';
3136 name = p.verbatim_item();
3141 if (p.next_token().cat() == catBegin) {
3142 command = p.verbatim_item();
3143 ert += '{' + command + '}';
3145 command = p.verbatim_item();
3148 // If command is known, make name known too, to parse
3149 // its arguments correctly. For this reason we also
3150 // have commands in syntax.default that are hardcoded.
3151 CommandMap::iterator it = known_commands.find(command);
3152 if (it != known_commands.end())
3153 known_commands[t.asInput()] = it->second;
3154 handle_ert(os, ert, context);
3157 else if (t.cs() == "hspace" || t.cs() == "vspace") {
3158 bool starred = false;
3159 if (p.next_token().asInput() == "*") {
3163 string name = t.asInput();
3164 string const length = p.verbatim_item();
3167 bool valid = splitLatexLength(length, valstring, unit);
3168 bool known_hspace = false;
3169 bool known_vspace = false;
3170 bool known_unit = false;
3173 istringstream iss(valstring);
3176 if (t.cs()[0] == 'h') {
3177 if (unit == "\\fill") {
3182 known_hspace = true;
3185 if (unit == "\\smallskipamount") {
3187 known_vspace = true;
3188 } else if (unit == "\\medskipamount") {
3190 known_vspace = true;
3191 } else if (unit == "\\bigskipamount") {
3193 known_vspace = true;
3194 } else if (unit == "\\fill") {
3196 known_vspace = true;
3200 if (!known_hspace && !known_vspace) {
3201 switch (unitFromString(unit)) {
3222 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
3223 // Literal horizontal length or known variable
3224 context.check_layout(os);
3225 begin_inset(os, "space ");
3233 if (known_unit && !known_hspace)
3235 << translate_len(length);
3237 } else if (known_unit || known_vspace) {
3238 // Literal vertical length or known variable
3239 context.check_layout(os);
3240 begin_inset(os, "VSpace ");
3248 // LyX can't handle other length variables in Inset VSpace/space
3253 handle_ert(os, name + '{' + unit + '}', context);
3254 else if (value == -1.0)
3255 handle_ert(os, name + "{-" + unit + '}', context);
3257 handle_ert(os, name + '{' + valstring + unit + '}', context);
3259 handle_ert(os, name + '{' + length + '}', context);
3263 // The single '=' is meant here.
3264 else if ((newinsetlayout = findInsetLayout(context.textclass, t.cs(), true))) {
3266 context.check_layout(os);
3267 begin_inset(os, "Flex ");
3268 os << to_utf8(newinsetlayout->name()) << '\n'
3269 << "status collapsed\n";
3270 parse_text_in_inset(p, os, FLAG_ITEM, false, context, newinsetlayout);
3275 // try to see whether the string is in unicodesymbols
3276 // Only use text mode commands, since we are in text mode here,
3277 // and math commands may be invalid (bug 6797)
3279 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
3280 rem, Encodings::TEXT_CMD);
3283 cerr << "When parsing " << t.cs()
3284 << ", result is " << to_utf8(s)
3285 << "+" << to_utf8(rem) << endl;
3286 context.check_layout(os);
3288 skip_spaces_braces(p);
3290 //cerr << "#: " << t << " mode: " << mode << endl;
3291 // heuristic: read up to next non-nested space
3293 string s = t.asInput();
3294 string z = p.verbatim_item();
3295 while (p.good() && z != " " && z.size()) {
3296 //cerr << "read: " << z << endl;
3298 z = p.verbatim_item();
3300 cerr << "found ERT: " << s << endl;
3301 handle_ert(os, s + ' ', context);
3304 string name = t.asInput();
3305 if (p.next_token().asInput() == "*") {
3306 // Starred commands like \vspace*{}
3307 p.get_token(); // Eat '*'
3310 if (!parse_command(name, p, os, outer, context))
3311 handle_ert(os, name, context);
3315 if (flags & FLAG_LEAVE) {
3316 flags &= ~FLAG_LEAVE;