2 * \file tex2lyx/text.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
10 * Full author contact details are available in file CREDITS.
21 #include "FloatList.h"
25 #include "support/lassert.h"
26 #include "support/convert.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/lstrings.h"
38 using namespace lyx::support;
43 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
44 Context const & context)
46 Context newcontext(true, context.textclass);
47 newcontext.font = context.font;
48 parse_text(p, os, flags, outer, newcontext);
49 newcontext.check_end_layout(os);
55 /// parses a paragraph snippet, useful for example for \\emph{...}
56 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context newcontext(context);
60 // Don't inherit the paragraph-level extra stuff
61 newcontext.par_extra_stuff.clear();
62 parse_text(p, os, flags, outer, newcontext);
63 // Make sure that we don't create invalid .lyx files
64 context.need_layout = newcontext.need_layout;
65 context.need_end_layout = newcontext.need_end_layout;
70 * Thin wrapper around parse_text_snippet() using a string.
72 * We completely ignore \c context.need_layout and \c context.need_end_layout,
73 * because our return value is not used directly (otherwise the stream version
74 * of parse_text_snippet() could be used). That means that the caller needs
75 * to do layout management manually.
76 * This is intended to parse text that does not create any layout changes.
78 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
81 Context newcontext(context);
82 newcontext.need_layout = false;
83 newcontext.need_end_layout = false;
84 newcontext.new_layout_allowed = false;
85 // Avoid warning by Context::~Context()
86 newcontext.par_extra_stuff.clear();
88 parse_text_snippet(p, os, flags, outer, newcontext);
93 char const * const known_ref_commands[] = { "ref", "pageref", "vref",
94 "vpageref", "prettyref", "eqref", 0 };
98 * The starred forms are also known except for "citefullauthor",
99 * "citeyear" and "citeyearpar".
101 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
102 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
103 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
107 * No starred form other than "cite*" known.
109 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
110 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
111 // jurabib commands not (yet) supported by LyX:
113 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
114 // "footciteauthor", "footciteyear", "footciteyearpar",
115 "citefield", "citetitle", 0 };
117 /// LaTeX names for quotes
118 char const * const known_quotes[] = { "dq", "guillemotleft", "flqq", "og",
119 "guillemotright", "frqq", "fg", "glq", "glqq", "textquoteleft", "grq", "grqq",
120 "quotedblbase", "textquotedblleft", "quotesinglbase", "textquoteright", "flq",
121 "guilsinglleft", "frq", "guilsinglright", 0};
123 /// the same as known_quotes with .lyx names
124 char const * const known_coded_quotes[] = { "prd", "ard", "ard", "ard",
125 "ald", "ald", "ald", "gls", "gld", "els", "els", "grd",
126 "gld", "grd", "gls", "ers", "fls",
127 "fls", "frs", "frs", 0};
129 /// LaTeX names for font sizes
130 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
131 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
133 /// the same as known_sizes with .lyx names plus a default entry
134 char const * const known_coded_sizes[] = { "default", "tiny", "scriptsize", "footnotesize",
135 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
137 /// LaTeX 2.09 names for font families
138 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
140 /// LaTeX names for font families
141 char const * const known_font_families[] = { "rmfamily", "sffamily",
144 /// the same as known_old_font_families and known_font_families with .lyx names
145 char const * const known_coded_font_families[] = { "roman", "sans",
148 /// LaTeX 2.09 names for font series
149 char const * const known_old_font_series[] = { "bf", 0};
151 /// LaTeX names for font series
152 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
154 /// the same as known_old_font_series and known_font_series with .lyx names
155 char const * const known_coded_font_series[] = { "bold", "medium", 0};
157 /// LaTeX 2.09 names for font shapes
158 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
160 /// LaTeX names for font shapes
161 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
164 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
165 char const * const known_coded_font_shapes[] = { "italic", "slanted",
166 "smallcaps", "up", 0};
169 * Graphics file extensions known by the dvips driver of the graphics package.
170 * These extensions are used to complete the filename of an included
171 * graphics file if it does not contain an extension.
172 * The order must be the same that latex uses to find a file, because we
173 * will use the first extension that matches.
174 * This is only an approximation for the common cases. If we would want to
175 * do it right in all cases, we would need to know which graphics driver is
176 * used and know the extensions of every driver of the graphics package.
178 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
179 "ps.gz", "eps.Z", "ps.Z", 0};
182 * Graphics file extensions known by the pdftex driver of the graphics package.
183 * \sa known_dvips_graphics_formats
185 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
189 * Known file extensions for TeX files as used by \\include.
191 char const * const known_tex_extensions[] = {"tex", 0};
193 /// spaces known by InsetSpace
194 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
195 "qquad", "enspace", "enskip", "negthinspace", "hfill", "dotfill", "hrulefill",
196 "leftarrowfill", "rightarrowfill", "upbracefill", "downbracefill", 0};
198 /// the same as known_spaces with .lyx names
199 char const * const known_coded_spaces[] = { "space{}", "space{}",
200 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
201 "negthinspace{}", "hfill{}", "dotfill{}", "hrulefill{}", "leftarrowfill{}",
202 "rightarrowfill{}", "upbracefill{}", "downbracefill{}", 0};
204 /// These are translated by LyX to commands like "\\LyX{}", so we have to put
205 /// them in ERT. "LaTeXe" must come before "LaTeX"!
206 char const * const known_phrases[] = {"LyX", "TeX", "LaTeXe", "LaTeX", 0};
207 char const * const known_coded_phrases[] = {"LyX", "TeX", "LaTeX2e", "LaTeX", 0};
208 int const known_phrase_lengths[] = {3, 5, 7, 0};
211 /// splits "x=z, y=b" into a map and an ordered keyword vector
212 void split_map(string const & s, map<string, string> & res, vector<string> & keys)
217 keys.resize(v.size());
218 for (size_t i = 0; i < v.size(); ++i) {
219 size_t const pos = v[i].find('=');
220 string const index = trim(v[i].substr(0, pos));
221 string const value = trim(v[i].substr(pos + 1, string::npos));
229 * Split a LaTeX length into value and unit.
230 * The latter can be a real unit like "pt", or a latex length variable
231 * like "\textwidth". The unit may contain additional stuff like glue
232 * lengths, but we don't care, because such lengths are ERT anyway.
233 * \returns true if \p value and \p unit are valid.
235 bool splitLatexLength(string const & len, string & value, string & unit)
239 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
240 //'4,5' is a valid LaTeX length number. Change it to '4.5'
241 string const length = subst(len, ',', '.');
242 if (i == string::npos)
245 if (len[0] == '\\') {
246 // We had something like \textwidth without a factor
252 value = trim(string(length, 0, i));
256 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
257 if (contains(len, '\\'))
258 unit = trim(string(len, i));
260 unit = ascii_lowercase(trim(string(len, i)));
265 /// A simple function to translate a latex length to something LyX can
266 /// understand. Not perfect, but rather best-effort.
267 bool translate_len(string const & length, string & valstring, string & unit)
269 if (!splitLatexLength(length, valstring, unit))
271 // LyX uses percent values
273 istringstream iss(valstring);
278 string const percentval = oss.str();
280 if (unit.empty() || unit[0] != '\\')
282 string::size_type const i = unit.find(' ');
283 string const endlen = (i == string::npos) ? string() : string(unit, i);
284 if (unit == "\\textwidth") {
285 valstring = percentval;
286 unit = "text%" + endlen;
287 } else if (unit == "\\columnwidth") {
288 valstring = percentval;
289 unit = "col%" + endlen;
290 } else if (unit == "\\paperwidth") {
291 valstring = percentval;
292 unit = "page%" + endlen;
293 } else if (unit == "\\linewidth") {
294 valstring = percentval;
295 unit = "line%" + endlen;
296 } else if (unit == "\\paperheight") {
297 valstring = percentval;
298 unit = "pheight%" + endlen;
299 } else if (unit == "\\textheight") {
300 valstring = percentval;
301 unit = "theight%" + endlen;
309 string translate_len(string const & length)
313 if (translate_len(length, value, unit))
315 // If the input is invalid, return what we have.
323 * Translates a LaTeX length into \p value, \p unit and
324 * \p special parts suitable for a box inset.
325 * The difference from translate_len() is that a box inset knows about
326 * some special "units" that are stored in \p special.
328 void translate_box_len(string const & length, string & value, string & unit, string & special)
330 if (translate_len(length, value, unit)) {
331 if (unit == "\\height" || unit == "\\depth" ||
332 unit == "\\totalheight" || unit == "\\width") {
333 special = unit.substr(1);
334 // The unit is not used, but LyX requires a dummy setting
347 * Find a file with basename \p name in path \p path and an extension
350 string find_file(string const & name, string const & path,
351 char const * const * extensions)
353 for (char const * const * what = extensions; *what; ++what) {
354 string const trial = addExtension(name, *what);
355 if (makeAbsPath(trial, path).exists())
362 void begin_inset(ostream & os, string const & name)
364 os << "\n\\begin_inset " << name;
368 void begin_command_inset(ostream & os, string const & name,
369 string const & latexname)
371 begin_inset(os, "CommandInset ");
372 os << name << "\nLatexCommand " << latexname << '\n';
376 void end_inset(ostream & os)
378 os << "\n\\end_inset\n\n";
382 bool skip_braces(Parser & p)
384 if (p.next_token().cat() != catBegin)
387 if (p.next_token().cat() == catEnd) {
396 void handle_ert(ostream & os, string const & s, Context & context)
398 // We must have a valid layout before outputting the ERT inset.
399 context.check_layout(os);
400 Context newcontext(true, context.textclass);
401 begin_inset(os, "ERT");
402 os << "\nstatus collapsed\n";
403 newcontext.check_layout(os);
404 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
406 os << "\n\\backslash\n";
407 else if (*it == '\n') {
408 newcontext.new_paragraph(os);
409 newcontext.check_layout(os);
413 newcontext.check_end_layout(os);
418 void handle_comment(ostream & os, string const & s, Context & context)
420 // TODO: Handle this better
421 Context newcontext(true, context.textclass);
422 begin_inset(os, "ERT");
423 os << "\nstatus collapsed\n";
424 newcontext.check_layout(os);
425 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
427 os << "\n\\backslash\n";
431 // make sure that our comment is the last thing on the line
432 newcontext.new_paragraph(os);
433 newcontext.check_layout(os);
434 newcontext.check_end_layout(os);
439 Layout const * findLayout(TextClass const & textclass, string const & name)
441 DocumentClass::const_iterator lit = textclass.begin();
442 DocumentClass::const_iterator len = textclass.end();
443 for (; lit != len; ++lit)
444 if (lit->latexname() == name)
450 void eat_whitespace(Parser &, ostream &, Context &, bool);
454 * Skips whitespace and braces.
455 * This should be called after a command has been parsed that is not put into
456 * ERT, and where LyX adds "{}" if needed.
458 void skip_spaces_braces(Parser & p, bool keepws = false)
460 /* The following four examples produce the same typeset output and
461 should be handled by this function:
469 // Unfortunately we need to skip comments, too.
470 // We can't use eat_whitespace since writing them after the {}
471 // results in different output in some cases.
472 bool const skipped_spaces = p.skip_spaces(true);
473 bool const skipped_braces = skip_braces(p);
474 if (keepws && skipped_spaces && !skipped_braces)
475 // put back the space (it is better handled by check_space)
476 p.unskip_spaces(true);
480 void output_command_layout(ostream & os, Parser & p, bool outer,
481 Context & parent_context,
482 Layout const * newlayout)
484 parent_context.check_end_layout(os);
485 Context context(true, parent_context.textclass, newlayout,
486 parent_context.layout, parent_context.font);
487 if (parent_context.deeper_paragraph) {
488 // We are beginning a nested environment after a
489 // deeper paragraph inside the outer list environment.
490 // Therefore we don't need to output a "begin deeper".
491 context.need_end_deeper = true;
493 context.check_deeper(os);
494 context.check_layout(os);
495 unsigned int optargs = 0;
496 while (optargs < context.layout->optargs) {
497 eat_whitespace(p, os, context, false);
498 if (p.next_token().character() != '[')
500 p.get_token(); // eat '['
501 begin_inset(os, "OptArg\n");
502 os << "status collapsed\n\n";
503 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
505 eat_whitespace(p, os, context, false);
509 // This is the code needed to parse required arguments, but
510 // required arguments come into being only much later than the
511 // file format tex2lyx is presently outputting.
512 unsigned int reqargs = 0;
513 while (reqargs < context.layout->reqargs) {
514 eat_whitespace(p, os, context, false);
515 if (p.next_token().character() != '{')
517 p.get_token(); // eat '{'
518 begin_inset(os, "OptArg\n");
519 os << "status collapsed\n\n";
520 parse_text_in_inset(p, os, FLAG_BRACE_LAST, outer, context);
522 eat_whitespace(p, os, context, false);
526 parse_text(p, os, FLAG_ITEM, outer, context);
527 context.check_end_layout(os);
528 if (parent_context.deeper_paragraph) {
529 // We must suppress the "end deeper" because we
530 // suppressed the "begin deeper" above.
531 context.need_end_deeper = false;
533 context.check_end_deeper(os);
534 // We don't need really a new paragraph, but
535 // we must make sure that the next item gets a \begin_layout.
536 parent_context.new_paragraph(os);
541 * Output a space if necessary.
542 * This function gets called for every whitespace token.
544 * We have three cases here:
545 * 1. A space must be suppressed. Example: The lyxcode case below
546 * 2. A space may be suppressed. Example: Spaces before "\par"
547 * 3. A space must not be suppressed. Example: A space between two words
549 * We currently handle only 1. and 3 and from 2. only the case of
550 * spaces before newlines as a side effect.
552 * 2. could be used to suppress as many spaces as possible. This has two effects:
553 * - Reimporting LyX generated LaTeX files changes almost no whitespace
554 * - Superflous whitespace from non LyX generated LaTeX files is removed.
555 * The drawback is that the logic inside the function becomes
556 * complicated, and that is the reason why it is not implemented.
558 void check_space(Parser & p, ostream & os, Context & context)
560 Token const next = p.next_token();
561 Token const curr = p.curr_token();
562 // A space before a single newline and vice versa must be ignored
563 // LyX emits a newline before \end{lyxcode}.
564 // This newline must be ignored,
565 // otherwise LyX will add an additional protected space.
566 if (next.cat() == catSpace ||
567 next.cat() == catNewline ||
568 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
571 context.check_layout(os);
577 * Parse all arguments of \p command
579 void parse_arguments(string const & command,
580 vector<ArgumentType> const & template_arguments,
581 Parser & p, ostream & os, bool outer, Context & context)
583 string ert = command;
584 size_t no_arguments = template_arguments.size();
585 for (size_t i = 0; i < no_arguments; ++i) {
586 switch (template_arguments[i]) {
588 // This argument contains regular LaTeX
589 handle_ert(os, ert + '{', context);
590 eat_whitespace(p, os, context, false);
591 parse_text(p, os, FLAG_ITEM, outer, context);
595 // This argument consists only of a single item.
596 // The presence of '{' or not must be preserved.
598 if (p.next_token().cat() == catBegin)
599 ert += '{' + p.verbatim_item() + '}';
601 ert += p.verbatim_item();
604 // This argument may contain special characters
605 ert += '{' + p.verbatim_item() + '}';
608 // true because we must not eat whitespace
609 ert += p.getOpt(true);
613 handle_ert(os, ert, context);
618 * Check whether \p command is a known command. If yes,
619 * handle the command with all arguments.
620 * \return true if the command was parsed, false otherwise.
622 bool parse_command(string const & command, Parser & p, ostream & os,
623 bool outer, Context & context)
625 if (known_commands.find(command) != known_commands.end()) {
626 parse_arguments(command, known_commands[command], p, os,
634 /// Parses a minipage or parbox
635 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
636 Context & parent_context, bool use_parbox)
640 // We need to set the height to the LaTeX default of 1\\totalheight
641 // for the case when no height argument is given
642 string height_value = "1";
643 string height_unit = "in";
644 string height_special = "totalheight";
647 position = p.getArg('[', ']');
648 if (position != "t" && position != "c" && position != "b") {
650 cerr << "invalid position for minipage/parbox" << endl;
653 latex_height = p.getArg('[', ']');
654 translate_box_len(latex_height, height_value, height_unit, height_special);
657 inner_pos = p.getArg('[', ']');
658 if (inner_pos != "c" && inner_pos != "t" &&
659 inner_pos != "b" && inner_pos != "s") {
660 inner_pos = position;
661 cerr << "invalid inner_pos for minipage/parbox"
669 string const latex_width = p.verbatim_item();
670 translate_len(latex_width, width_value, width_unit);
671 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
672 // LyX can't handle length variables
677 ss << "\\begin{minipage}";
678 if (!position.empty())
679 ss << '[' << position << ']';
680 if (!latex_height.empty())
681 ss << '[' << latex_height << ']';
682 if (!inner_pos.empty())
683 ss << '[' << inner_pos << ']';
684 ss << "{" << latex_width << "}";
687 handle_ert(os, ss.str(), parent_context);
688 parent_context.new_paragraph(os);
689 parse_text_in_inset(p, os, flags, outer, parent_context);
691 handle_ert(os, "}", parent_context);
693 handle_ert(os, "\\end{minipage}", parent_context);
695 // LyX does not like empty positions, so we have
696 // to set them to the LaTeX default values here.
697 if (position.empty())
699 if (inner_pos.empty())
700 inner_pos = position;
701 parent_context.check_layout(os);
702 begin_inset(os, "Box Frameless\n");
703 os << "position \"" << position << "\"\n";
704 os << "hor_pos \"c\"\n";
705 os << "has_inner_box 1\n";
706 os << "inner_pos \"" << inner_pos << "\"\n";
707 os << "use_parbox " << use_parbox << "\n";
708 os << "width \"" << width_value << width_unit << "\"\n";
709 os << "special \"none\"\n";
710 os << "height \"" << height_value << height_unit << "\"\n";
711 os << "height_special \"" << height_special << "\"\n";
712 os << "status open\n\n";
713 parse_text_in_inset(p, os, flags, outer, parent_context);
715 #ifdef PRESERVE_LAYOUT
716 // LyX puts a % after the end of the minipage
717 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
719 //handle_comment(os, "%dummy", parent_context);
722 parent_context.new_paragraph(os);
724 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
725 //handle_comment(os, "%dummy", parent_context);
728 // We add a protected space if something real follows
729 if (p.good() && p.next_token().cat() != catComment) {
730 begin_inset(os, "space ~\n");
739 /// parse an unknown environment
740 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
741 unsigned flags, bool outer,
742 Context & parent_context)
744 if (name == "tabbing")
745 // We need to remember that we have to handle '\=' specially
746 flags |= FLAG_TABBING;
748 // We need to translate font changes and paragraphs inside the
749 // environment to ERT if we have a non standard font.
750 // Otherwise things like
751 // \large\begin{foo}\huge bar\end{foo}
753 bool const specialfont =
754 (parent_context.font != parent_context.normalfont);
755 bool const new_layout_allowed = parent_context.new_layout_allowed;
757 parent_context.new_layout_allowed = false;
758 handle_ert(os, "\\begin{" + name + "}", parent_context);
759 parse_text_snippet(p, os, flags, outer, parent_context);
760 handle_ert(os, "\\end{" + name + "}", parent_context);
762 parent_context.new_layout_allowed = new_layout_allowed;
766 void parse_environment(Parser & p, ostream & os, bool outer,
767 string & last_env, Context & parent_context)
769 Layout const * newlayout;
770 string const name = p.getArg('{', '}');
771 const bool is_starred = suffixIs(name, '*');
772 string const unstarred_name = rtrim(name, "*");
773 active_environments.push_back(name);
775 if (is_math_env(name)) {
776 parent_context.check_layout(os);
777 begin_inset(os, "Formula ");
778 os << "\\begin{" << name << "}";
779 parse_math(p, os, FLAG_END, MATH_MODE);
780 os << "\\end{" << name << "}";
784 else if (name == "tabular" || name == "longtable") {
785 eat_whitespace(p, os, parent_context, false);
786 parent_context.check_layout(os);
787 begin_inset(os, "Tabular ");
788 handle_tabular(p, os, name == "longtable", parent_context);
793 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
794 eat_whitespace(p, os, parent_context, false);
795 parent_context.check_layout(os);
796 begin_inset(os, "Float " + unstarred_name + "\n");
798 os << "placement " << p.getArg('[', ']') << '\n';
799 os << "wide " << convert<string>(is_starred)
800 << "\nsideways false"
801 << "\nstatus open\n\n";
802 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
804 // We don't need really a new paragraph, but
805 // we must make sure that the next item gets a \begin_layout.
806 parent_context.new_paragraph(os);
810 else if (name == "minipage") {
811 eat_whitespace(p, os, parent_context, false);
812 parse_box(p, os, FLAG_END, outer, parent_context, false);
816 else if (name == "comment") {
817 eat_whitespace(p, os, parent_context, false);
818 parent_context.check_layout(os);
819 begin_inset(os, "Note Comment\n");
820 os << "status open\n";
821 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
824 skip_braces(p); // eat {} that might by set by LyX behind comments
827 else if (name == "lyxgreyedout") {
828 eat_whitespace(p, os, parent_context, false);
829 parent_context.check_layout(os);
830 begin_inset(os, "Note Greyedout\n");
831 os << "status open\n";
832 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
837 else if (name == "framed" || name == "shaded") {
838 eat_whitespace(p, os, parent_context, false);
839 parent_context.check_layout(os);
840 if (name == "framed")
841 begin_inset(os, "Box Framed\n");
843 begin_inset(os, "Box Shaded\n");
844 os << "position \"t\"\n"
849 "width \"100col%\"\n"
852 "height_special \"totalheight\"\n"
854 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
859 else if (!parent_context.new_layout_allowed)
860 parse_unknown_environment(p, name, os, FLAG_END, outer,
863 // Alignment and spacing settings
864 // FIXME (bug xxxx): These settings can span multiple paragraphs and
865 // therefore are totally broken!
866 // Note that \centering, raggedright, and raggedleft cannot be handled, as
867 // they are commands not environments. They are furthermore switches that
868 // can be ended by another switches, but also by commands like \footnote or
869 // \parbox. So the only safe way is to leave them untouched.
870 else if (name == "center" || name == "centering" ||
871 name == "flushleft" || name == "flushright" ||
872 name == "singlespace" || name == "onehalfspace" ||
873 name == "doublespace" || name == "spacing") {
874 eat_whitespace(p, os, parent_context, false);
875 // We must begin a new paragraph if not already done
876 if (! parent_context.atParagraphStart()) {
877 parent_context.check_end_layout(os);
878 parent_context.new_paragraph(os);
880 if (name == "flushleft")
881 parent_context.add_extra_stuff("\\align left\n");
882 else if (name == "flushright")
883 parent_context.add_extra_stuff("\\align right\n");
884 else if (name == "center" || name == "centering")
885 parent_context.add_extra_stuff("\\align center\n");
886 else if (name == "singlespace")
887 parent_context.add_extra_stuff("\\paragraph_spacing single\n");
888 else if (name == "onehalfspace")
889 parent_context.add_extra_stuff("\\paragraph_spacing onehalf\n");
890 else if (name == "doublespace")
891 parent_context.add_extra_stuff("\\paragraph_spacing double\n");
892 else if (name == "spacing")
893 parent_context.add_extra_stuff("\\paragraph_spacing other " + p.verbatim_item() + "\n");
894 parse_text(p, os, FLAG_END, outer, parent_context);
895 // Just in case the environment is empty
896 parent_context.extra_stuff.erase();
897 // We must begin a new paragraph to reset the alignment
898 parent_context.new_paragraph(os);
902 // The single '=' is meant here.
903 else if ((newlayout = findLayout(parent_context.textclass, name)) &&
904 newlayout->isEnvironment()) {
905 eat_whitespace(p, os, parent_context, false);
906 Context context(true, parent_context.textclass, newlayout,
907 parent_context.layout, parent_context.font);
908 if (parent_context.deeper_paragraph) {
909 // We are beginning a nested environment after a
910 // deeper paragraph inside the outer list environment.
911 // Therefore we don't need to output a "begin deeper".
912 context.need_end_deeper = true;
914 parent_context.check_end_layout(os);
915 if (last_env == name) {
916 // we need to output a separator since LyX would export
917 // the two environments as one otherwise (bug 5716)
918 docstring const sep = from_ascii("--Separator--");
919 TeX2LyXDocClass const & textclass(parent_context.textclass);
920 if (textclass.hasLayout(sep)) {
921 Context newcontext(parent_context);
922 newcontext.layout = &(textclass[sep]);
923 newcontext.check_layout(os);
924 newcontext.check_end_layout(os);
926 parent_context.check_layout(os);
927 begin_inset(os, "Note Note\n");
928 os << "status closed\n";
929 Context newcontext(true, textclass,
930 &(textclass.defaultLayout()));
931 newcontext.check_layout(os);
932 newcontext.check_end_layout(os);
934 parent_context.check_end_layout(os);
937 switch (context.layout->latextype) {
938 case LATEX_LIST_ENVIRONMENT:
939 context.add_par_extra_stuff("\\labelwidthstring "
940 + p.verbatim_item() + '\n');
943 case LATEX_BIB_ENVIRONMENT:
944 p.verbatim_item(); // swallow next arg
950 context.check_deeper(os);
951 parse_text(p, os, FLAG_END, outer, context);
952 context.check_end_layout(os);
953 if (parent_context.deeper_paragraph) {
954 // We must suppress the "end deeper" because we
955 // suppressed the "begin deeper" above.
956 context.need_end_deeper = false;
958 context.check_end_deeper(os);
959 parent_context.new_paragraph(os);
963 else if (name == "appendix") {
964 // This is no good latex style, but it works and is used in some documents...
965 eat_whitespace(p, os, parent_context, false);
966 parent_context.check_end_layout(os);
967 Context context(true, parent_context.textclass, parent_context.layout,
968 parent_context.layout, parent_context.font);
969 context.check_layout(os);
970 os << "\\start_of_appendix\n";
971 parse_text(p, os, FLAG_END, outer, context);
972 context.check_end_layout(os);
976 else if (known_environments.find(name) != known_environments.end()) {
977 vector<ArgumentType> arguments = known_environments[name];
978 // The last "argument" denotes wether we may translate the
979 // environment contents to LyX
980 // The default required if no argument is given makes us
981 // compatible with the reLyXre environment.
982 ArgumentType contents = arguments.empty() ?
985 if (!arguments.empty())
986 arguments.pop_back();
987 // See comment in parse_unknown_environment()
988 bool const specialfont =
989 (parent_context.font != parent_context.normalfont);
990 bool const new_layout_allowed =
991 parent_context.new_layout_allowed;
993 parent_context.new_layout_allowed = false;
994 parse_arguments("\\begin{" + name + "}", arguments, p, os,
995 outer, parent_context);
996 if (contents == verbatim)
997 handle_ert(os, p.verbatimEnvironment(name),
1000 parse_text_snippet(p, os, FLAG_END, outer,
1002 handle_ert(os, "\\end{" + name + "}", parent_context);
1004 parent_context.new_layout_allowed = new_layout_allowed;
1008 parse_unknown_environment(p, name, os, FLAG_END, outer,
1012 active_environments.pop_back();
1016 /// parses a comment and outputs it to \p os.
1017 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
1019 LASSERT(t.cat() == catComment, return);
1020 if (!t.cs().empty()) {
1021 context.check_layout(os);
1022 handle_comment(os, '%' + t.cs(), context);
1023 if (p.next_token().cat() == catNewline) {
1024 // A newline after a comment line starts a new
1026 if (context.new_layout_allowed) {
1027 if(!context.atParagraphStart())
1028 // Only start a new paragraph if not already
1029 // done (we might get called recursively)
1030 context.new_paragraph(os);
1032 handle_ert(os, "\n", context);
1033 eat_whitespace(p, os, context, true);
1036 // "%\n" combination
1043 * Reads spaces and comments until the first non-space, non-comment token.
1044 * New paragraphs (double newlines or \\par) are handled like simple spaces
1045 * if \p eatParagraph is true.
1046 * Spaces are skipped, but comments are written to \p os.
1048 void eat_whitespace(Parser & p, ostream & os, Context & context,
1052 Token const & t = p.get_token();
1053 if (t.cat() == catComment)
1054 parse_comment(p, os, t, context);
1055 else if ((! eatParagraph && p.isParagraph()) ||
1056 (t.cat() != catSpace && t.cat() != catNewline)) {
1065 * Set a font attribute, parse text and reset the font attribute.
1066 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
1067 * \param currentvalue Current value of the attribute. Is set to the new
1068 * value during parsing.
1069 * \param newvalue New value of the attribute
1071 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
1072 Context & context, string const & attribute,
1073 string & currentvalue, string const & newvalue)
1075 context.check_layout(os);
1076 string const oldvalue = currentvalue;
1077 currentvalue = newvalue;
1078 os << '\n' << attribute << ' ' << newvalue << "\n";
1079 parse_text_snippet(p, os, flags, outer, context);
1080 context.check_layout(os);
1081 os << '\n' << attribute << ' ' << oldvalue << "\n";
1082 currentvalue = oldvalue;
1086 /// get the arguments of a natbib or jurabib citation command
1087 void get_cite_arguments(Parser & p, bool natbibOrder,
1088 string & before, string & after)
1090 // We need to distinguish "" and "[]", so we can't use p.getOpt().
1092 // text before the citation
1094 // text after the citation
1095 after = p.getFullOpt();
1097 if (!after.empty()) {
1098 before = p.getFullOpt();
1099 if (natbibOrder && !before.empty())
1100 swap(before, after);
1105 /// Convert filenames with TeX macros and/or quotes to something LyX
1107 string const normalize_filename(string const & name)
1109 Parser p(trim(name, "\""));
1112 Token const & t = p.get_token();
1113 if (t.cat() != catEscape)
1115 else if (t.cs() == "lyxdot") {
1116 // This is used by LyX for simple dots in relative
1120 } else if (t.cs() == "space") {
1130 /// Convert \p name from TeX convention (relative to master file) to LyX
1131 /// convention (relative to .lyx file) if it is relative
1132 void fix_relative_filename(string & name)
1134 if (FileName::isAbsolute(name))
1137 name = to_utf8(makeRelPath(from_utf8(makeAbsPath(name, getMasterFilePath()).absFileName()),
1138 from_utf8(getParentFilePath())));
1142 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1143 void parse_noweb(Parser & p, ostream & os, Context & context)
1145 // assemble the rest of the keyword
1149 Token const & t = p.get_token();
1150 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1153 scrap = (p.good() && p.next_token().asInput() == "=");
1155 name += p.get_token().asInput();
1158 name += t.asInput();
1161 if (!scrap || !context.new_layout_allowed ||
1162 !context.textclass.hasLayout(from_ascii("Scrap"))) {
1163 cerr << "Warning: Could not interpret '" << name
1164 << "'. Ignoring it." << endl;
1168 // We use new_paragraph instead of check_end_layout because the stuff
1169 // following the noweb chunk needs to start with a \begin_layout.
1170 // This may create a new paragraph even if there was none in the
1171 // noweb file, but the alternative is an invalid LyX file. Since
1172 // noweb code chunks are implemented with a layout style in LyX they
1173 // always must be in an own paragraph.
1174 context.new_paragraph(os);
1175 Context newcontext(true, context.textclass,
1176 &context.textclass[from_ascii("Scrap")]);
1177 newcontext.check_layout(os);
1180 Token const & t = p.get_token();
1181 // We abuse the parser a bit, because this is no TeX syntax
1183 if (t.cat() == catEscape)
1184 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1187 begin_inset(oss, "Newline newline");
1189 os << subst(t.asInput(), "\n", oss.str());
1191 // The scrap chunk is ended by an @ at the beginning of a line.
1192 // After the @ the line may contain a comment and/or
1193 // whitespace, but nothing else.
1194 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1195 (p.next_token().cat() == catSpace ||
1196 p.next_token().cat() == catNewline ||
1197 p.next_token().cat() == catComment)) {
1198 while (p.good() && p.next_token().cat() == catSpace)
1199 os << p.get_token().asInput();
1200 if (p.next_token().cat() == catComment)
1201 // The comment includes a final '\n'
1202 os << p.get_token().asInput();
1204 if (p.next_token().cat() == catNewline)
1211 newcontext.check_end_layout(os);
1215 /// detects \\def, \\long\\def and \\global\\long\\def with ws and comments
1216 bool is_macro(Parser & p)
1218 Token first = p.curr_token();
1219 if (first.cat() != catEscape || !p.good())
1221 if (first.cs() == "def")
1223 if (first.cs() != "global" && first.cs() != "long")
1225 Token second = p.get_token();
1227 while (p.good() && !p.isParagraph() && (second.cat() == catSpace ||
1228 second.cat() == catNewline || second.cat() == catComment)) {
1229 second = p.get_token();
1232 bool secondvalid = second.cat() == catEscape;
1234 bool thirdvalid = false;
1235 if (p.good() && first.cs() == "global" && secondvalid &&
1236 second.cs() == "long") {
1237 third = p.get_token();
1239 while (p.good() && !p.isParagraph() &&
1240 (third.cat() == catSpace ||
1241 third.cat() == catNewline ||
1242 third.cat() == catComment)) {
1243 third = p.get_token();
1246 thirdvalid = third.cat() == catEscape;
1248 for (int i = 0; i < pos; ++i)
1253 return (first.cs() == "global" || first.cs() == "long") &&
1254 second.cs() == "def";
1255 return first.cs() == "global" && second.cs() == "long" &&
1256 third.cs() == "def";
1260 /// Parse a macro definition (assumes that is_macro() returned true)
1261 void parse_macro(Parser & p, ostream & os, Context & context)
1263 context.check_layout(os);
1264 Token first = p.curr_token();
1267 string command = first.asInput();
1268 if (first.cs() != "def") {
1270 eat_whitespace(p, os, context, false);
1271 second = p.curr_token();
1272 command += second.asInput();
1273 if (second.cs() != "def") {
1275 eat_whitespace(p, os, context, false);
1276 third = p.curr_token();
1277 command += third.asInput();
1280 eat_whitespace(p, os, context, false);
1281 string const name = p.get_token().cs();
1282 eat_whitespace(p, os, context, false);
1288 while (p.next_token().cat() != catBegin) {
1289 if (p.next_token().cat() == catParameter) {
1294 // followed by number?
1295 if (p.next_token().cat() == catOther) {
1296 char c = p.getChar();
1298 // number = current arity + 1?
1299 if (c == arity + '0' + 1)
1304 paramtext += p.get_token().cs();
1306 paramtext += p.get_token().cs();
1311 // only output simple (i.e. compatible) macro as FormulaMacros
1312 string ert = '\\' + name + ' ' + paramtext + '{' + p.verbatim_item() + '}';
1314 context.check_layout(os);
1315 begin_inset(os, "FormulaMacro");
1316 os << "\n\\def" << ert;
1319 handle_ert(os, command + ert, context);
1322 } // anonymous namespace
1325 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1328 Layout const * newlayout = 0;
1329 // Store the latest bibliographystyle and nocite{*} option
1330 // (needed for bibtex inset)
1332 string bibliographystyle;
1333 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1334 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1337 Token const & t = p.get_token();
1340 cerr << "t: " << t << " flags: " << flags << "\n";
1343 if (flags & FLAG_ITEM) {
1344 if (t.cat() == catSpace)
1347 flags &= ~FLAG_ITEM;
1348 if (t.cat() == catBegin) {
1349 // skip the brace and collect everything to the next matching
1351 flags |= FLAG_BRACE_LAST;
1355 // handle only this single token, leave the loop if done
1356 flags |= FLAG_LEAVE;
1359 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1361 if (t.character() == '}' && (flags & FLAG_BRACE_LAST))
1364 // If there is anything between \end{env} and \begin{env} we
1365 // don't need to output a separator.
1366 if (t.cat() != catSpace && t.cat() != catNewline &&
1367 t.asInput() != "\\begin")
1373 if (t.cat() == catMath) {
1374 // we are inside some text mode thingy, so opening new math is allowed
1375 context.check_layout(os);
1376 begin_inset(os, "Formula ");
1377 Token const & n = p.get_token();
1378 if (n.cat() == catMath && outer) {
1379 // TeX's $$...$$ syntax for displayed math
1381 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1383 p.get_token(); // skip the second '$' token
1385 // simple $...$ stuff
1388 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1394 else if (t.cat() == catSuper || t.cat() == catSub)
1395 cerr << "catcode " << t << " illegal in text mode\n";
1397 // Basic support for english quotes. This should be
1398 // extended to other quotes, but is not so easy (a
1399 // left english quote is the same as a right german
1401 else if (t.asInput() == "`" && p.next_token().asInput() == "`") {
1402 context.check_layout(os);
1403 begin_inset(os, "Quotes ");
1409 else if (t.asInput() == "'" && p.next_token().asInput() == "'") {
1410 context.check_layout(os);
1411 begin_inset(os, "Quotes ");
1418 else if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1419 context.check_layout(os);
1420 begin_inset(os, "Quotes ");
1427 else if (t.asInput() == "<" && p.next_token().asInput() == "<") {
1428 context.check_layout(os);
1429 begin_inset(os, "Quotes ");
1436 else if (t.asInput() == "<"
1437 && p.next_token().asInput() == "<" && noweb_mode) {
1439 parse_noweb(p, os, context);
1442 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1443 check_space(p, os, context);
1445 else if (t.character() == '[' && noweb_mode &&
1446 p.next_token().character() == '[') {
1447 // These can contain underscores
1449 string const s = p.getFullOpt() + ']';
1450 if (p.next_token().character() == ']')
1453 cerr << "Warning: Inserting missing ']' in '"
1454 << s << "'." << endl;
1455 handle_ert(os, s, context);
1458 else if (t.cat() == catLetter) {
1459 context.check_layout(os);
1460 // Workaround for bug 4752.
1461 // FIXME: This whole code block needs to be removed
1462 // when the bug is fixed and tex2lyx produces
1463 // the updated file format.
1464 // The replacement algorithm in LyX is so stupid that
1465 // it even translates a phrase if it is part of a word.
1466 bool handled = false;
1467 for (int const * l = known_phrase_lengths; *l; ++l) {
1468 string phrase = t.cs();
1469 for (int i = 1; i < *l && p.next_token().isAlnumASCII(); ++i)
1470 phrase += p.get_token().cs();
1471 if (is_known(phrase, known_coded_phrases)) {
1472 handle_ert(os, phrase, context);
1476 for (size_t i = 1; i < phrase.length(); ++i)
1484 else if (t.cat() == catOther ||
1485 t.cat() == catAlign ||
1486 t.cat() == catParameter) {
1487 // This translates "&" to "\\&" which may be wrong...
1488 context.check_layout(os);
1492 else if (p.isParagraph()) {
1493 if (context.new_layout_allowed)
1494 context.new_paragraph(os);
1496 handle_ert(os, "\\par ", context);
1497 eat_whitespace(p, os, context, true);
1500 else if (t.cat() == catActive) {
1501 context.check_layout(os);
1502 if (t.character() == '~') {
1503 if (context.layout->free_spacing)
1506 begin_inset(os, "space ~\n");
1513 else if (t.cat() == catBegin &&
1514 p.next_token().cat() == catEnd) {
1516 Token const prev = p.prev_token();
1518 if (p.next_token().character() == '`' ||
1519 (prev.character() == '-' &&
1520 p.next_token().character() == '-'))
1521 ; // ignore it in {}`` or -{}-
1523 handle_ert(os, "{}", context);
1527 else if (t.cat() == catBegin) {
1528 context.check_layout(os);
1529 // special handling of font attribute changes
1530 Token const prev = p.prev_token();
1531 Token const next = p.next_token();
1532 TeXFont const oldFont = context.font;
1533 if (next.character() == '[' ||
1534 next.character() == ']' ||
1535 next.character() == '*') {
1537 if (p.next_token().cat() == catEnd) {
1542 handle_ert(os, "{", context);
1543 parse_text_snippet(p, os,
1546 handle_ert(os, "}", context);
1548 } else if (! context.new_layout_allowed) {
1549 handle_ert(os, "{", context);
1550 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1552 handle_ert(os, "}", context);
1553 } else if (is_known(next.cs(), known_sizes)) {
1554 // next will change the size, so we must
1556 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1558 if (!context.atParagraphStart())
1560 << context.font.size << "\n";
1561 } else if (is_known(next.cs(), known_font_families)) {
1562 // next will change the font family, so we
1563 // must reset it here
1564 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1566 if (!context.atParagraphStart())
1568 << context.font.family << "\n";
1569 } else if (is_known(next.cs(), known_font_series)) {
1570 // next will change the font series, so we
1571 // must reset it here
1572 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1574 if (!context.atParagraphStart())
1576 << context.font.series << "\n";
1577 } else if (is_known(next.cs(), known_font_shapes)) {
1578 // next will change the font shape, so we
1579 // must reset it here
1580 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1582 if (!context.atParagraphStart())
1584 << context.font.shape << "\n";
1585 } else if (is_known(next.cs(), known_old_font_families) ||
1586 is_known(next.cs(), known_old_font_series) ||
1587 is_known(next.cs(), known_old_font_shapes)) {
1588 // next will change the font family, series
1589 // and shape, so we must reset it here
1590 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1592 if (!context.atParagraphStart())
1594 << context.font.family
1596 << context.font.series
1598 << context.font.shape << "\n";
1600 handle_ert(os, "{", context);
1601 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1603 handle_ert(os, "}", context);
1607 else if (t.cat() == catEnd) {
1608 if (flags & FLAG_BRACE_LAST) {
1611 cerr << "stray '}' in text\n";
1612 handle_ert(os, "}", context);
1615 else if (t.cat() == catComment)
1616 parse_comment(p, os, t, context);
1619 // control sequences
1622 else if (t.cs() == "(") {
1623 context.check_layout(os);
1624 begin_inset(os, "Formula");
1626 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1631 else if (t.cs() == "[") {
1632 context.check_layout(os);
1633 begin_inset(os, "Formula");
1635 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1640 else if (t.cs() == "begin")
1641 parse_environment(p, os, outer, last_env, context);
1643 else if (t.cs() == "end") {
1644 if (flags & FLAG_END) {
1645 // eat environment name
1646 string const name = p.getArg('{', '}');
1647 if (name != active_environment())
1648 cerr << "\\end{" + name + "} does not match \\begin{"
1649 + active_environment() + "}\n";
1652 p.error("found 'end' unexpectedly");
1655 else if (t.cs() == "item") {
1658 bool optarg = false;
1659 if (p.next_token().character() == '[') {
1660 p.get_token(); // eat '['
1661 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1666 context.check_layout(os);
1667 if (context.has_item) {
1668 // An item in an unknown list-like environment
1669 // FIXME: Do this in check_layout()!
1670 context.has_item = false;
1672 handle_ert(os, "\\item", context);
1674 handle_ert(os, "\\item ", context);
1677 if (context.layout->labeltype != LABEL_MANUAL) {
1678 // LyX does not support \item[\mybullet]
1679 // in itemize environments
1680 handle_ert(os, "[", context);
1682 handle_ert(os, "]", context);
1683 } else if (!s.empty()) {
1684 // The space is needed to separate the
1685 // item from the rest of the sentence.
1687 eat_whitespace(p, os, context, false);
1692 else if (t.cs() == "bibitem") {
1694 context.check_layout(os);
1695 begin_command_inset(os, "bibitem", "bibitem");
1696 os << "label \"" << p.getOptContent() << "\"\n";
1697 os << "key \"" << p.verbatim_item() << "\"\n";
1701 else if (is_macro(p))
1702 parse_macro(p, os, context);
1704 else if (t.cs() == "noindent") {
1706 context.add_par_extra_stuff("\\noindent\n");
1709 else if (t.cs() == "appendix") {
1710 context.add_par_extra_stuff("\\start_of_appendix\n");
1711 // We need to start a new paragraph. Otherwise the
1712 // appendix in 'bla\appendix\chapter{' would start
1714 context.new_paragraph(os);
1715 // We need to make sure that the paragraph is
1716 // generated even if it is empty. Otherwise the
1717 // appendix in '\par\appendix\par\chapter{' would
1719 context.check_layout(os);
1720 // FIXME: This is a hack to prevent paragraph
1721 // deletion if it is empty. Handle this better!
1723 "%dummy comment inserted by tex2lyx to "
1724 "ensure that this paragraph is not empty",
1726 // Both measures above may generate an additional
1727 // empty paragraph, but that does not hurt, because
1728 // whitespace does not matter here.
1729 eat_whitespace(p, os, context, true);
1732 // Starred section headings
1733 // Must attempt to parse "Section*" before "Section".
1734 else if ((p.next_token().asInput() == "*") &&
1735 context.new_layout_allowed &&
1736 (newlayout = findLayout(context.textclass, t.cs() + '*')) &&
1737 newlayout->isCommand()) {
1738 TeXFont const oldFont = context.font;
1739 // save the current font size
1740 string const size = oldFont.size;
1741 // reset the font size to default, because the
1742 // font size switches don't affect section
1743 // headings and the like
1744 context.font.size = known_coded_sizes[0];
1745 output_font_change(os, oldFont, context.font);
1748 output_command_layout(os, p, outer, context, newlayout);
1749 // set the font size to the original value
1750 context.font.size = size;
1751 output_font_change(os, oldFont, context.font);
1755 // Section headings and the like
1756 else if (context.new_layout_allowed &&
1757 (newlayout = findLayout(context.textclass, t.cs())) &&
1758 newlayout->isCommand()) {
1759 TeXFont const oldFont = context.font;
1760 // save the current font size
1761 string const size = oldFont.size;
1762 // reset the font size to default, because the font size switches don't
1763 // affect section headings and the like
1764 context.font.size = known_coded_sizes[0];
1765 output_font_change(os, oldFont, context.font);
1767 output_command_layout(os, p, outer, context, newlayout);
1768 // set the font size to the original value
1769 context.font.size = size;
1770 output_font_change(os, oldFont, context.font);
1774 else if (t.cs() == "caption") {
1775 // FIXME: this should get some cleanup. All
1776 // the \begin_layout:s are output by the
1779 context.check_layout(os);
1781 begin_inset(os, "Caption\n\n");
1782 os << "\\begin_layout "
1783 << to_utf8(context.textclass.defaultLayout().name())
1785 if (p.next_token().character() == '[') {
1786 p.get_token(); // eat '['
1787 begin_inset(os, "OptArg\n");
1788 os << "status collapsed\n";
1789 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
1791 eat_whitespace(p, os, context, false);
1793 parse_text(p, os, FLAG_ITEM, outer, context);
1794 context.check_end_layout(os);
1795 // We don't need really a new paragraph, but
1796 // we must make sure that the next item gets a \begin_layout.
1797 context.new_paragraph(os);
1800 os << "\\end_layout\n";
1803 else if (t.cs() == "includegraphics") {
1804 bool const clip = p.next_token().asInput() == "*";
1807 string const arg = p.getArg('[', ']');
1808 map<string, string> opts;
1809 vector<string> keys;
1810 split_map(arg, opts, keys);
1812 opts["clip"] = string();
1813 string name = normalize_filename(p.verbatim_item());
1815 string const path = getMasterFilePath();
1816 // We want to preserve relative / absolute filenames,
1817 // therefore path is only used for testing
1818 if (!makeAbsPath(name, path).exists()) {
1819 // The file extension is probably missing.
1820 // Now try to find it out.
1821 string const dvips_name =
1822 find_file(name, path,
1823 known_dvips_graphics_formats);
1824 string const pdftex_name =
1825 find_file(name, path,
1826 known_pdftex_graphics_formats);
1827 if (!dvips_name.empty()) {
1828 if (!pdftex_name.empty()) {
1829 cerr << "This file contains the "
1831 "\"\\includegraphics{"
1833 "However, files\n\""
1834 << dvips_name << "\" and\n\""
1835 << pdftex_name << "\"\n"
1836 "both exist, so I had to make a "
1837 "choice and took the first one.\n"
1838 "Please move the unwanted one "
1839 "someplace else and try again\n"
1840 "if my choice was wrong."
1844 } else if (!pdftex_name.empty()) {
1850 if (makeAbsPath(name, path).exists())
1851 fix_relative_filename(name);
1853 cerr << "Warning: Could not find graphics file '"
1854 << name << "'." << endl;
1856 context.check_layout(os);
1857 begin_inset(os, "Graphics ");
1858 os << "\n\tfilename " << name << '\n';
1859 if (opts.find("width") != opts.end())
1861 << translate_len(opts["width"]) << '\n';
1862 if (opts.find("height") != opts.end())
1864 << translate_len(opts["height"]) << '\n';
1865 if (opts.find("scale") != opts.end()) {
1866 istringstream iss(opts["scale"]);
1870 os << "\tscale " << val << '\n';
1872 if (opts.find("angle") != opts.end()) {
1873 os << "\trotateAngle "
1874 << opts["angle"] << '\n';
1875 vector<string>::const_iterator a =
1876 find(keys.begin(), keys.end(), "angle");
1877 vector<string>::const_iterator s =
1878 find(keys.begin(), keys.end(), "width");
1879 if (s == keys.end())
1880 s = find(keys.begin(), keys.end(), "height");
1881 if (s == keys.end())
1882 s = find(keys.begin(), keys.end(), "scale");
1883 if (s != keys.end() && distance(s, a) > 0)
1884 os << "\tscaleBeforeRotation\n";
1886 if (opts.find("origin") != opts.end()) {
1888 string const opt = opts["origin"];
1889 if (opt.find('l') != string::npos) ss << "left";
1890 if (opt.find('r') != string::npos) ss << "right";
1891 if (opt.find('c') != string::npos) ss << "center";
1892 if (opt.find('t') != string::npos) ss << "Top";
1893 if (opt.find('b') != string::npos) ss << "Bottom";
1894 if (opt.find('B') != string::npos) ss << "Baseline";
1895 if (!ss.str().empty())
1896 os << "\trotateOrigin " << ss.str() << '\n';
1898 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1900 if (opts.find("keepaspectratio") != opts.end())
1901 os << "\tkeepAspectRatio\n";
1902 if (opts.find("clip") != opts.end())
1904 if (opts.find("draft") != opts.end())
1906 if (opts.find("bb") != opts.end())
1907 os << "\tBoundingBox "
1908 << opts["bb"] << '\n';
1909 int numberOfbbOptions = 0;
1910 if (opts.find("bbllx") != opts.end())
1911 numberOfbbOptions++;
1912 if (opts.find("bblly") != opts.end())
1913 numberOfbbOptions++;
1914 if (opts.find("bburx") != opts.end())
1915 numberOfbbOptions++;
1916 if (opts.find("bbury") != opts.end())
1917 numberOfbbOptions++;
1918 if (numberOfbbOptions == 4)
1919 os << "\tBoundingBox "
1920 << opts["bbllx"] << " " << opts["bblly"] << " "
1921 << opts["bburx"] << " " << opts["bbury"] << '\n';
1922 else if (numberOfbbOptions > 0)
1923 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1924 numberOfbbOptions = 0;
1925 if (opts.find("natwidth") != opts.end())
1926 numberOfbbOptions++;
1927 if (opts.find("natheight") != opts.end())
1928 numberOfbbOptions++;
1929 if (numberOfbbOptions == 2)
1930 os << "\tBoundingBox 0bp 0bp "
1931 << opts["natwidth"] << " " << opts["natheight"] << '\n';
1932 else if (numberOfbbOptions > 0)
1933 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1934 ostringstream special;
1935 if (opts.find("hiresbb") != opts.end())
1936 special << "hiresbb,";
1937 if (opts.find("trim") != opts.end())
1939 if (opts.find("viewport") != opts.end())
1940 special << "viewport=" << opts["viewport"] << ',';
1941 if (opts.find("totalheight") != opts.end())
1942 special << "totalheight=" << opts["totalheight"] << ',';
1943 if (opts.find("type") != opts.end())
1944 special << "type=" << opts["type"] << ',';
1945 if (opts.find("ext") != opts.end())
1946 special << "ext=" << opts["ext"] << ',';
1947 if (opts.find("read") != opts.end())
1948 special << "read=" << opts["read"] << ',';
1949 if (opts.find("command") != opts.end())
1950 special << "command=" << opts["command"] << ',';
1951 string s_special = special.str();
1952 if (!s_special.empty()) {
1953 // We had special arguments. Remove the trailing ','.
1954 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1956 // TODO: Handle the unknown settings better.
1957 // Warn about invalid options.
1958 // Check whether some option was given twice.
1962 else if (t.cs() == "footnote" ||
1963 (t.cs() == "thanks" && context.layout->intitle)) {
1965 context.check_layout(os);
1966 begin_inset(os, "Foot\n");
1967 os << "status collapsed\n\n";
1968 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1972 else if (t.cs() == "marginpar") {
1974 context.check_layout(os);
1975 begin_inset(os, "Marginal\n");
1976 os << "status collapsed\n\n";
1977 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1981 else if (t.cs() == "ensuremath") {
1983 context.check_layout(os);
1984 string const s = p.verbatim_item();
1985 //FIXME: this never triggers in UTF8
1986 if (s == "\xb1" || s == "\xb3" || s == "\xb2" || s == "\xb5")
1989 handle_ert(os, "\\ensuremath{" + s + "}",
1993 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1994 // FIXME: Somehow prevent title layouts if
1995 // "maketitle" was not found
1997 skip_spaces_braces(p);
2000 else if (t.cs() == "tableofcontents") {
2001 context.check_layout(os);
2002 begin_command_inset(os, "toc", "tableofcontents");
2004 skip_spaces_braces(p);
2007 else if (t.cs() == "listoffigures") {
2008 context.check_layout(os);
2009 begin_inset(os, "FloatList figure\n");
2011 skip_spaces_braces(p);
2014 else if (t.cs() == "listoftables") {
2015 context.check_layout(os);
2016 begin_inset(os, "FloatList table\n");
2018 skip_spaces_braces(p);
2021 else if (t.cs() == "listof") {
2022 p.skip_spaces(true);
2023 string const name = p.get_token().cs();
2024 if (context.textclass.floats().typeExist(name)) {
2025 context.check_layout(os);
2026 begin_inset(os, "FloatList ");
2029 p.get_token(); // swallow second arg
2031 handle_ert(os, "\\listof{" + name + "}", context);
2034 else if (t.cs() == "textrm")
2035 parse_text_attributes(p, os, FLAG_ITEM, outer,
2036 context, "\\family",
2037 context.font.family, "roman");
2039 else if (t.cs() == "textsf")
2040 parse_text_attributes(p, os, FLAG_ITEM, outer,
2041 context, "\\family",
2042 context.font.family, "sans");
2044 else if (t.cs() == "texttt")
2045 parse_text_attributes(p, os, FLAG_ITEM, outer,
2046 context, "\\family",
2047 context.font.family, "typewriter");
2049 else if (t.cs() == "textmd")
2050 parse_text_attributes(p, os, FLAG_ITEM, outer,
2051 context, "\\series",
2052 context.font.series, "medium");
2054 else if (t.cs() == "textbf")
2055 parse_text_attributes(p, os, FLAG_ITEM, outer,
2056 context, "\\series",
2057 context.font.series, "bold");
2059 else if (t.cs() == "textup")
2060 parse_text_attributes(p, os, FLAG_ITEM, outer,
2062 context.font.shape, "up");
2064 else if (t.cs() == "textit")
2065 parse_text_attributes(p, os, FLAG_ITEM, outer,
2067 context.font.shape, "italic");
2069 else if (t.cs() == "textsl")
2070 parse_text_attributes(p, os, FLAG_ITEM, outer,
2072 context.font.shape, "slanted");
2074 else if (t.cs() == "textsc")
2075 parse_text_attributes(p, os, FLAG_ITEM, outer,
2077 context.font.shape, "smallcaps");
2079 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
2080 context.check_layout(os);
2081 TeXFont oldFont = context.font;
2082 context.font.init();
2083 context.font.size = oldFont.size;
2084 os << "\n\\family " << context.font.family << "\n";
2085 os << "\n\\series " << context.font.series << "\n";
2086 os << "\n\\shape " << context.font.shape << "\n";
2087 if (t.cs() == "textnormal") {
2088 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2089 output_font_change(os, context.font, oldFont);
2090 context.font = oldFont;
2092 eat_whitespace(p, os, context, false);
2095 else if (t.cs() == "textcolor") {
2096 // scheme is \textcolor{color name}{text}
2097 string const color = p.verbatim_item();
2098 // we only support the predefined colors of the color package
2099 if (color == "black" || color == "blue" || color == "cyan"
2100 || color == "green" || color == "magenta" || color == "red"
2101 || color == "white" || color == "yellow") {
2102 context.check_layout(os);
2103 os << "\n\\color " << color << "\n";
2104 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2105 context.check_layout(os);
2106 os << "\n\\color inherit\n";
2108 // for custom defined colors
2109 handle_ert(os, t.asInput() + "{" + color + "}", context);
2112 else if (t.cs() == "underbar") {
2113 // Do NOT handle \underline.
2114 // \underbar cuts through y, g, q, p etc.,
2115 // \underline does not.
2116 context.check_layout(os);
2117 os << "\n\\bar under\n";
2118 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2119 context.check_layout(os);
2120 os << "\n\\bar default\n";
2123 else if (t.cs() == "emph" || t.cs() == "noun") {
2124 context.check_layout(os);
2125 os << "\n\\" << t.cs() << " on\n";
2126 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
2127 context.check_layout(os);
2128 os << "\n\\" << t.cs() << " default\n";
2131 else if (t.cs() == "lyxline") {
2132 context.check_layout(os);
2136 else if (is_known(t.cs(), known_phrases)) {
2137 // FIXME: This needs to be changed when bug 4752 is fixed.
2138 char const * const * where = is_known(t.cs(), known_phrases);
2139 context.check_layout(os);
2140 os << known_coded_phrases[where - known_phrases];
2141 skip_spaces_braces(p);
2144 else if (is_known(t.cs(), known_ref_commands)) {
2145 context.check_layout(os);
2146 begin_command_inset(os, "ref", t.cs());
2147 // LyX cannot handle newlines in a latex command
2148 // FIXME: Move the substitution into parser::getOpt()?
2149 os << subst(p.getOpt(), "\n", " ");
2150 os << "reference " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2154 else if (use_natbib &&
2155 is_known(t.cs(), known_natbib_commands) &&
2156 ((t.cs() != "citefullauthor" &&
2157 t.cs() != "citeyear" &&
2158 t.cs() != "citeyearpar") ||
2159 p.next_token().asInput() != "*")) {
2160 context.check_layout(os);
2161 string command = t.cs();
2162 if (p.next_token().asInput() == "*") {
2166 if (command == "citefullauthor")
2167 // alternative name for "\\citeauthor*"
2168 command = "citeauthor*";
2170 // text before the citation
2172 // text after the citation
2174 get_cite_arguments(p, true, before, after);
2176 if (command == "cite") {
2177 // \cite without optional argument means
2178 // \citet, \cite with at least one optional
2179 // argument means \citep.
2180 if (before.empty() && after.empty())
2185 if (before.empty() && after == "[]")
2186 // avoid \citet[]{a}
2188 else if (before == "[]" && after == "[]") {
2189 // avoid \citet[][]{a}
2193 // remove the brackets around after and before
2194 if (!after.empty()) {
2196 after.erase(after.length() - 1, 1);
2197 // LyX cannot handle newlines in the parameter
2198 after = subst(after, "\n", " ");
2200 if (!before.empty()) {
2202 before.erase(before.length() - 1, 1);
2203 // LyX cannot handle newlines in the parameter
2204 before = subst(before, "\n", " ");
2206 begin_command_inset(os, "citation", command);
2207 os << "after " << '"' << after << '"' << "\n";
2208 os << "before " << '"' << before << '"' << "\n";
2209 os << "key " << '"' << p.verbatim_item() << '"' << "\n";
2213 else if (use_jurabib &&
2214 is_known(t.cs(), known_jurabib_commands) &&
2215 (t.cs() == "cite" || p.next_token().asInput() != "*")) {
2216 context.check_layout(os);
2217 string command = t.cs();
2218 if (p.next_token().asInput() == "*") {
2222 char argumentOrder = '\0';
2223 vector<string> const & options = used_packages["jurabib"];
2224 if (find(options.begin(), options.end(),
2225 "natbiborder") != options.end())
2226 argumentOrder = 'n';
2227 else if (find(options.begin(), options.end(),
2228 "jurabiborder") != options.end())
2229 argumentOrder = 'j';
2231 // text before the citation
2233 // text after the citation
2235 get_cite_arguments(p, argumentOrder != 'j', before, after);
2237 string const citation = p.verbatim_item();
2238 if (!before.empty() && argumentOrder == '\0') {
2239 cerr << "Warning: Assuming argument order "
2240 "of jurabib version 0.6 for\n'"
2241 << command << before << after << '{'
2242 << citation << "}'.\n"
2243 "Add 'jurabiborder' to the jurabib "
2244 "package options if you used an\n"
2245 "earlier jurabib version." << endl;
2247 if (!after.empty()) {
2249 after.erase(after.length() - 1, 1);
2251 if (!before.empty()) {
2253 before.erase(before.length() - 1, 1);
2255 begin_command_inset(os, "citation", command);
2256 os << "after " << '"' << after << '"' << "\n";
2257 os << "before " << '"' << before << '"' << "\n";
2258 os << "key " << '"' << citation << '"' << "\n";
2262 else if (t.cs() == "cite"
2263 || t.cs() == "nocite") {
2264 context.check_layout(os);
2265 // LyX cannot handle newlines in a latex command
2266 string after = subst(p.getOptContent(), "\n", " ");
2267 string key = subst(p.verbatim_item(), "\n", " ");
2268 // store the case that it is "\nocite{*}" to use it later for
2271 begin_command_inset(os, "citation", t.cs());
2272 os << "after " << '"' << after << '"' << "\n";
2273 os << "key " << '"' << key << '"' << "\n";
2279 else if (t.cs() == "index") {
2280 context.check_layout(os);
2281 begin_inset(os, "Index\n");
2282 os << "status collapsed\n";
2283 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2287 else if (t.cs() == "nomenclature") {
2288 context.check_layout(os);
2289 begin_command_inset(os, "nomenclature", "nomenclature");
2290 // LyX cannot handle newlines in a latex command
2291 string prefix = subst(p.getOptContent(), "\n", " ");
2292 if (!prefix.empty())
2293 os << "prefix " << '"' << prefix << '"' << "\n";
2294 os << "symbol " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2295 os << "description " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2299 else if (t.cs() == "label") {
2300 context.check_layout(os);
2301 begin_command_inset(os, "label", "label");
2302 // LyX cannot handle newlines in a latex command
2303 os << "name " << '"' << subst(p.verbatim_item(), "\n", " ") << '"' << "\n";
2307 else if (t.cs() == "printindex") {
2308 context.check_layout(os);
2309 begin_command_inset(os, "index_print", "printindex");
2311 skip_spaces_braces(p);
2314 else if (t.cs() == "printnomenclature") {
2315 context.check_layout(os);
2316 begin_command_inset(os, "nomencl_print", "printnomenclature");
2318 skip_spaces_braces(p);
2321 else if (t.cs() == "url") {
2322 context.check_layout(os);
2323 begin_inset(os, "Flex URL\n");
2324 os << "status collapsed\n";
2325 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2329 else if (LYX_FORMAT >= 408 &&
2330 (t.cs() == "textsuperscript" || t.cs() == "textsubscript")) {
2331 context.check_layout(os);
2332 begin_inset(os, "script ");
2333 os << t.cs().substr(4) << '\n';
2334 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
2338 else if (is_known(t.cs(), known_quotes)) {
2339 char const * const * where = is_known(t.cs(), known_quotes);
2340 context.check_layout(os);
2341 begin_inset(os, "Quotes ");
2342 os << known_coded_quotes[where - known_quotes];
2344 // LyX adds {} after the quote, so we have to eat
2345 // spaces here if there are any before a possible
2347 eat_whitespace(p, os, context, false);
2351 else if (is_known(t.cs(), known_sizes) &&
2352 context.new_layout_allowed) {
2353 char const * const * where = is_known(t.cs(), known_sizes);
2354 context.check_layout(os);
2355 TeXFont const oldFont = context.font;
2356 // the font size index differs by 1, because the known_coded_sizes
2357 // has additionally a "default" entry
2358 context.font.size = known_coded_sizes[where - known_sizes + 1];
2359 output_font_change(os, oldFont, context.font);
2360 eat_whitespace(p, os, context, false);
2363 else if (is_known(t.cs(), known_font_families) &&
2364 context.new_layout_allowed) {
2365 char const * const * where =
2366 is_known(t.cs(), known_font_families);
2367 context.check_layout(os);
2368 TeXFont const oldFont = context.font;
2369 context.font.family =
2370 known_coded_font_families[where - known_font_families];
2371 output_font_change(os, oldFont, context.font);
2372 eat_whitespace(p, os, context, false);
2375 else if (is_known(t.cs(), known_font_series) &&
2376 context.new_layout_allowed) {
2377 char const * const * where =
2378 is_known(t.cs(), known_font_series);
2379 context.check_layout(os);
2380 TeXFont const oldFont = context.font;
2381 context.font.series =
2382 known_coded_font_series[where - known_font_series];
2383 output_font_change(os, oldFont, context.font);
2384 eat_whitespace(p, os, context, false);
2387 else if (is_known(t.cs(), known_font_shapes) &&
2388 context.new_layout_allowed) {
2389 char const * const * where =
2390 is_known(t.cs(), known_font_shapes);
2391 context.check_layout(os);
2392 TeXFont const oldFont = context.font;
2393 context.font.shape =
2394 known_coded_font_shapes[where - known_font_shapes];
2395 output_font_change(os, oldFont, context.font);
2396 eat_whitespace(p, os, context, false);
2398 else if (is_known(t.cs(), known_old_font_families) &&
2399 context.new_layout_allowed) {
2400 char const * const * where =
2401 is_known(t.cs(), known_old_font_families);
2402 context.check_layout(os);
2403 TeXFont const oldFont = context.font;
2404 context.font.init();
2405 context.font.size = oldFont.size;
2406 context.font.family =
2407 known_coded_font_families[where - known_old_font_families];
2408 output_font_change(os, oldFont, context.font);
2409 eat_whitespace(p, os, context, false);
2412 else if (is_known(t.cs(), known_old_font_series) &&
2413 context.new_layout_allowed) {
2414 char const * const * where =
2415 is_known(t.cs(), known_old_font_series);
2416 context.check_layout(os);
2417 TeXFont const oldFont = context.font;
2418 context.font.init();
2419 context.font.size = oldFont.size;
2420 context.font.series =
2421 known_coded_font_series[where - known_old_font_series];
2422 output_font_change(os, oldFont, context.font);
2423 eat_whitespace(p, os, context, false);
2426 else if (is_known(t.cs(), known_old_font_shapes) &&
2427 context.new_layout_allowed) {
2428 char const * const * where =
2429 is_known(t.cs(), known_old_font_shapes);
2430 context.check_layout(os);
2431 TeXFont const oldFont = context.font;
2432 context.font.init();
2433 context.font.size = oldFont.size;
2434 context.font.shape =
2435 known_coded_font_shapes[where - known_old_font_shapes];
2436 output_font_change(os, oldFont, context.font);
2437 eat_whitespace(p, os, context, false);
2440 else if (t.cs() == "selectlanguage") {
2441 context.check_layout(os);
2442 // save the language for the case that a
2443 // \foreignlanguage is used
2445 context.font.language = subst(p.verbatim_item(), "\n", " ");
2446 os << "\\lang " << context.font.language << "\n";
2449 else if (t.cs() == "foreignlanguage") {
2450 context.check_layout(os);
2451 os << "\n\\lang " << subst(p.verbatim_item(), "\n", " ") << "\n";
2452 os << subst(p.verbatim_item(), "\n", " ");
2453 // FIXME: the second argument of selectlanguage
2454 // has to be parsed (like for \textsf, for
2456 // set back to last selectlanguage
2457 os << "\n\\lang " << context.font.language << "\n";
2460 else if (t.cs() == "inputencoding") {
2461 // nothing to write here
2462 string const enc = subst(p.verbatim_item(), "\n", " ");
2466 else if (t.cs() == "ldots") {
2467 context.check_layout(os);
2468 os << "\\SpecialChar \\ldots{}\n";
2469 skip_spaces_braces(p);
2472 else if (t.cs() == "lyxarrow") {
2473 context.check_layout(os);
2474 os << "\\SpecialChar \\menuseparator\n";
2475 skip_spaces_braces(p);
2478 else if (t.cs() == "textcompwordmark") {
2479 context.check_layout(os);
2480 os << "\\SpecialChar \\textcompwordmark{}\n";
2481 skip_spaces_braces(p);
2484 else if (t.cs() == "slash") {
2485 context.check_layout(os);
2486 os << "\\SpecialChar \\slash{}\n";
2487 skip_spaces_braces(p);
2490 else if (t.cs() == "nobreakdash" && p.next_token().asInput() == "-") {
2491 context.check_layout(os);
2492 os << "\\SpecialChar \\nobreakdash-\n";
2496 else if (t.cs() == "textquotedbl") {
2497 context.check_layout(os);
2502 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2503 context.check_layout(os);
2504 os << "\\SpecialChar \\@.\n";
2508 else if (t.cs() == "-") {
2509 context.check_layout(os);
2510 os << "\\SpecialChar \\-\n";
2513 else if (t.cs() == "textasciitilde") {
2514 context.check_layout(os);
2516 skip_spaces_braces(p);
2519 else if (t.cs() == "textasciicircum") {
2520 context.check_layout(os);
2522 skip_spaces_braces(p);
2525 else if (t.cs() == "textbackslash") {
2526 context.check_layout(os);
2527 os << "\n\\backslash\n";
2528 skip_spaces_braces(p);
2531 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2532 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2534 context.check_layout(os);
2538 else if (t.cs() == "char") {
2539 context.check_layout(os);
2540 if (p.next_token().character() == '`') {
2542 if (p.next_token().cs() == "\"") {
2547 handle_ert(os, "\\char`", context);
2550 handle_ert(os, "\\char", context);
2554 else if (t.cs() == "verb") {
2555 context.check_layout(os);
2556 char const delimiter = p.next_token().character();
2557 string const arg = p.getArg(delimiter, delimiter);
2559 oss << "\\verb" << delimiter << arg << delimiter;
2560 handle_ert(os, oss.str(), context);
2563 // Problem: \= creates a tabstop inside the tabbing environment
2564 // and else an accent. In the latter case we really would want
2565 // \={o} instead of \= o.
2566 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2567 handle_ert(os, t.asInput(), context);
2569 // accents (see Table 6 in Comprehensive LaTeX Symbol List)
2570 else if (t.cs().size() == 1
2571 && contains("\"'.=^`bcdHkrtuv~", t.cs())) {
2572 context.check_layout(os);
2573 // try to see whether the string is in unicodesymbols
2575 string command = t.asInput() + "{"
2576 + trim(p.verbatim_item())
2578 docstring s = encodings.fromLaTeXCommand(from_utf8(command), rem);
2581 cerr << "When parsing " << command
2582 << ", result is " << to_utf8(s)
2583 << "+" << to_utf8(rem) << endl;
2586 // we did not find a non-ert version
2587 handle_ert(os, command, context);
2590 else if (t.cs() == "\\") {
2591 context.check_layout(os);
2593 handle_ert(os, "\\\\" + p.getOpt(), context);
2594 else if (p.next_token().asInput() == "*") {
2596 // getOpt() eats the following space if there
2597 // is no optional argument, but that is OK
2598 // here since it has no effect in the output.
2599 handle_ert(os, "\\\\*" + p.getOpt(), context);
2602 begin_inset(os, "Newline newline");
2607 else if (t.cs() == "newline" ||
2608 (t.cs() == "linebreak" && !p.hasOpt())) {
2609 context.check_layout(os);
2610 begin_inset(os, "Newline ");
2613 skip_spaces_braces(p);
2616 else if (t.cs() == "input" || t.cs() == "include"
2617 || t.cs() == "verbatiminput") {
2618 string name = t.cs();
2619 if (t.cs() == "verbatiminput"
2620 && p.next_token().asInput() == "*")
2621 name += p.get_token().asInput();
2622 context.check_layout(os);
2623 string filename(normalize_filename(p.getArg('{', '}')));
2624 string const path = getMasterFilePath();
2625 // We want to preserve relative / absolute filenames,
2626 // therefore path is only used for testing
2627 if ((t.cs() == "include" || t.cs() == "input") &&
2628 !makeAbsPath(filename, path).exists()) {
2629 // The file extension is probably missing.
2630 // Now try to find it out.
2631 string const tex_name =
2632 find_file(filename, path,
2633 known_tex_extensions);
2634 if (!tex_name.empty())
2635 filename = tex_name;
2637 bool external = false;
2639 if (makeAbsPath(filename, path).exists()) {
2640 string const abstexname =
2641 makeAbsPath(filename, path).absFileName();
2642 string const abslyxname =
2643 changeExtension(abstexname, ".lyx");
2644 string const absfigname =
2645 changeExtension(abstexname, ".fig");
2646 fix_relative_filename(filename);
2647 string const lyxname =
2648 changeExtension(filename, ".lyx");
2650 external = FileName(absfigname).exists();
2651 if (t.cs() == "input") {
2652 string const ext = getExtension(abstexname);
2654 // Combined PS/LaTeX:
2655 // x.eps, x.pstex_t (old xfig)
2656 // x.pstex, x.pstex_t (new xfig, e.g. 3.2.5)
2657 FileName const absepsname(
2658 changeExtension(abstexname, ".eps"));
2659 FileName const abspstexname(
2660 changeExtension(abstexname, ".pstex"));
2661 bool const xfigeps =
2662 (absepsname.exists() ||
2663 abspstexname.exists()) &&
2666 // Combined PDF/LaTeX:
2667 // x.pdf, x.pdftex_t (old xfig)
2668 // x.pdf, x.pdf_t (new xfig, e.g. 3.2.5)
2669 FileName const abspdfname(
2670 changeExtension(abstexname, ".pdf"));
2671 bool const xfigpdf =
2672 abspdfname.exists() &&
2673 (ext == "pdftex_t" || ext == "pdf_t");
2677 // Combined PS/PDF/LaTeX:
2678 // x_pspdftex.eps, x_pspdftex.pdf, x.pspdftex
2679 string const absbase2(
2680 removeExtension(abstexname) + "_pspdftex");
2681 FileName const abseps2name(
2682 addExtension(absbase2, ".eps"));
2683 FileName const abspdf2name(
2684 addExtension(absbase2, ".pdf"));
2685 bool const xfigboth =
2686 abspdf2name.exists() &&
2687 abseps2name.exists() && ext == "pspdftex";
2689 xfig = xfigpdf || xfigeps || xfigboth;
2690 external = external && xfig;
2693 outname = changeExtension(filename, ".fig");
2695 // Don't try to convert, the result
2696 // would be full of ERT.
2698 } else if (t.cs() != "verbatiminput" &&
2699 tex2lyx(abstexname, FileName(abslyxname),
2706 cerr << "Warning: Could not find included file '"
2707 << filename << "'." << endl;
2711 begin_inset(os, "External\n");
2712 os << "\ttemplate XFig\n"
2713 << "\tfilename " << outname << '\n';
2715 begin_command_inset(os, "include", name);
2716 os << "preview false\n"
2717 "filename \"" << outname << "\"\n";
2722 else if (t.cs() == "bibliographystyle") {
2723 // store new bibliographystyle
2724 bibliographystyle = p.verbatim_item();
2725 // output new bibliographystyle.
2726 // This is only necessary if used in some other macro than \bibliography.
2727 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2730 else if (t.cs() == "bibliography") {
2731 context.check_layout(os);
2732 begin_command_inset(os, "bibtex", "bibtex");
2733 if (!btprint.empty()) {
2734 os << "btprint " << '"' << "btPrintAll" << '"' << "\n";
2735 // clear the string because the next BibTeX inset can be without the
2736 // \nocite{*} option
2739 os << "bibfiles " << '"' << p.verbatim_item() << '"' << "\n";
2740 // Do we have a bibliographystyle set?
2741 if (!bibliographystyle.empty())
2742 os << "options " << '"' << bibliographystyle << '"' << "\n";
2746 else if (t.cs() == "parbox")
2747 parse_box(p, os, FLAG_ITEM, outer, context, true);
2749 //\makebox() is part of the picture environment and different from \makebox{}
2750 //\makebox{} will be parsed by parse_box when bug 2956 is fixed
2751 else if (t.cs() == "makebox") {
2752 string arg = t.asInput();
2753 if (p.next_token().character() == '(')
2754 //the syntax is: \makebox(x,y)[position]{content}
2755 arg += p.getFullParentheseArg();
2757 //the syntax is: \makebox[width][position]{content}
2758 arg += p.getFullOpt();
2759 handle_ert(os, arg + p.getFullOpt(), context);
2762 else if (t.cs() == "smallskip" ||
2763 t.cs() == "medskip" ||
2764 t.cs() == "bigskip" ||
2765 t.cs() == "vfill") {
2766 context.check_layout(os);
2767 begin_inset(os, "VSpace ");
2770 skip_spaces_braces(p);
2773 else if (is_known(t.cs(), known_spaces)) {
2774 char const * const * where = is_known(t.cs(), known_spaces);
2775 context.check_layout(os);
2776 begin_inset(os, "space ");
2777 os << '\\' << known_coded_spaces[where - known_spaces]
2780 // LaTeX swallows whitespace after all spaces except
2781 // "\\,". We have to do that here, too, because LyX
2782 // adds "{}" which would make the spaces significant.
2784 eat_whitespace(p, os, context, false);
2785 // LyX adds "{}" after all spaces except "\\ " and
2786 // "\\,", so we have to remove "{}".
2787 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2788 // remove the braces after "\\,", too.
2793 else if (t.cs() == "newpage" ||
2794 (t.cs() == "pagebreak" && !p.hasOpt()) ||
2795 t.cs() == "clearpage" ||
2796 t.cs() == "cleardoublepage") {
2797 context.check_layout(os);
2798 begin_inset(os, "Newpage ");
2801 skip_spaces_braces(p);
2804 else if (t.cs() == "newcommand" ||
2805 t.cs() == "providecommand" ||
2806 t.cs() == "renewcommand") {
2807 // providecommand could be handled by parse_command(),
2808 // but we need to call add_known_command() here.
2809 string name = t.asInput();
2810 if (p.next_token().asInput() == "*") {
2811 // Starred form. Eat '*'
2815 string const command = p.verbatim_item();
2816 string const opt1 = p.getOpt();
2817 string const opt2 = p.getFullOpt();
2818 add_known_command(command, opt1, !opt2.empty());
2819 string const ert = name + '{' + command + '}' +
2821 '{' + p.verbatim_item() + '}';
2823 if (t.cs() == "providecommand")
2824 handle_ert(os, ert, context);
2826 context.check_layout(os);
2827 begin_inset(os, "FormulaMacro");
2833 else if (t.cs() == "let" && p.next_token().asInput() != "*") {
2834 // let could be handled by parse_command(),
2835 // but we need to call add_known_command() here.
2836 string ert = t.asInput();
2839 if (p.next_token().cat() == catBegin) {
2840 name = p.verbatim_item();
2841 ert += '{' + name + '}';
2843 name = p.verbatim_item();
2848 if (p.next_token().cat() == catBegin) {
2849 command = p.verbatim_item();
2850 ert += '{' + command + '}';
2852 command = p.verbatim_item();
2855 // If command is known, make name known too, to parse
2856 // its arguments correctly. For this reason we also
2857 // have commands in syntax.default that are hardcoded.
2858 CommandMap::iterator it = known_commands.find(command);
2859 if (it != known_commands.end())
2860 known_commands[t.asInput()] = it->second;
2861 handle_ert(os, ert, context);
2864 else if (t.cs() == "hspace" || t.cs() == "vspace") {
2865 bool starred = false;
2866 if (p.next_token().asInput() == "*") {
2870 string name = t.asInput();
2871 string const length = p.verbatim_item();
2874 bool valid = splitLatexLength(length, valstring, unit);
2875 bool known_hspace = false;
2876 bool known_vspace = false;
2877 bool known_unit = false;
2880 istringstream iss(valstring);
2883 if (t.cs()[0] == 'h') {
2884 if (unit == "\\fill") {
2889 known_hspace = true;
2892 if (unit == "\\smallskipamount") {
2894 known_vspace = true;
2895 } else if (unit == "\\medskipamount") {
2897 known_vspace = true;
2898 } else if (unit == "\\bigskipamount") {
2900 known_vspace = true;
2901 } else if (unit == "\\fill") {
2903 known_vspace = true;
2907 if (!known_hspace && !known_vspace) {
2908 switch (unitFromString(unit)) {
2929 if (t.cs()[0] == 'h' && (known_unit || known_hspace)) {
2930 // Literal horizontal length or known variable
2931 context.check_layout(os);
2932 begin_inset(os, "space ");
2940 if (known_unit && !known_hspace)
2942 << translate_len(length);
2944 } else if (known_unit || known_vspace) {
2945 // Literal vertical length or known variable
2946 context.check_layout(os);
2947 begin_inset(os, "VSpace ");
2955 // LyX can't handle other length variables in Inset VSpace/space
2960 handle_ert(os, name + '{' + unit + '}', context);
2961 else if (value == -1.0)
2962 handle_ert(os, name + "{-" + unit + '}', context);
2964 handle_ert(os, name + '{' + valstring + unit + '}', context);
2966 handle_ert(os, name + '{' + length + '}', context);
2971 // try to see whether the string is in unicodesymbols
2972 // Only use text mode commands, since we are in text mode here,
2973 // and math commands may be invalid (bug 6797)
2975 docstring s = encodings.fromLaTeXCommand(from_utf8(t.asInput()),
2976 rem, Encodings::TEXT_CMD);
2979 cerr << "When parsing " << t.cs()
2980 << ", result is " << to_utf8(s)
2981 << "+" << to_utf8(rem) << endl;
2982 context.check_layout(os);
2984 skip_spaces_braces(p);
2986 //cerr << "#: " << t << " mode: " << mode << endl;
2987 // heuristic: read up to next non-nested space
2989 string s = t.asInput();
2990 string z = p.verbatim_item();
2991 while (p.good() && z != " " && z.size()) {
2992 //cerr << "read: " << z << endl;
2994 z = p.verbatim_item();
2996 cerr << "found ERT: " << s << endl;
2997 handle_ert(os, s + ' ', context);
3000 string name = t.asInput();
3001 if (p.next_token().asInput() == "*") {
3002 // Starred commands like \vspace*{}
3003 p.get_token(); // Eat '*'
3006 if (!parse_command(name, p, os, outer, context))
3007 handle_ert(os, name, context);
3011 if (flags & FLAG_LEAVE) {
3012 flags &= ~FLAG_LEAVE;