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
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
32 using lyx::support::ChangeExtension;
33 using lyx::support::MakeAbsPath;
34 using lyx::support::rtrim;
35 using lyx::support::suffixIs;
36 using lyx::support::contains;
37 using lyx::support::subst;
44 using std::ostringstream;
45 using std::istringstream;
49 namespace fs = boost::filesystem;
52 /// thin wrapper around parse_text using a string
53 string parse_text(Parser & p, unsigned flags, const bool outer,
57 parse_text(p, os, flags, outer, context);
62 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
65 Context newcontext(true, context.textclass);
66 newcontext.font = context.font;
67 parse_text(p, os, flags, outer, newcontext);
68 newcontext.check_end_layout(os);
72 /// parses a paragraph snippet, useful for example for \emph{...}
73 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
76 Context newcontext(false, context.textclass);
77 newcontext.font = context.font;
78 parse_text(p, os, flags, outer, newcontext);
79 // should not be needed
80 newcontext.check_end_layout(os);
86 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
87 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
91 * We can't put these into known_latex_commands because the argument order
92 * is reversed in lyx if there are 2 arguments.
93 * The starred forms are also known.
95 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
96 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
97 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
101 * We can't put these into known_latex_commands because the argument order
102 * is reversed in lyx if there are 2 arguments.
103 * No starred form other than "cite*" known.
105 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
106 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
107 // jurabib commands not (yet) supported by LyX:
108 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
109 // "footciteauthor", "footciteyear", "footciteyearpar",
110 "citefield", "citetitle", "cite*", 0 };
112 /// LaTeX names for quotes
113 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
114 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
116 /// the same as known_quotes with .lyx names
117 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
118 "grd", "gls", "fls", "frd", 0};
120 /// LaTeX names for font sizes
121 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
122 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
124 /// the same as known_sizes with .lyx names
125 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
126 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
128 /// LaTeX 2.09 names for font families
129 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
131 /// LaTeX names for font families
132 char const * const known_font_families[] = { "rmfamily", "sffamily",
135 /// the same as known_old_font_families and known_font_families with .lyx names
136 char const * const known_coded_font_families[] = { "roman", "sans",
139 /// LaTeX 2.09 names for font series
140 char const * const known_old_font_series[] = { "bf", 0};
142 /// LaTeX names for font series
143 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
145 /// the same as known_old_font_series and known_font_series with .lyx names
146 char const * const known_coded_font_series[] = { "bold", "medium", 0};
148 /// LaTeX 2.09 names for font shapes
149 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
151 /// LaTeX names for font shapes
152 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
155 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
156 char const * const known_coded_font_shapes[] = { "italic", "slanted",
157 "smallcaps", "up", 0};
160 * Graphics file extensions known by the dvips driver of the graphics package.
161 * These extensions are used to complete the filename of an included
162 * graphics file if it does not contain an extension.
163 * The order must be the same that latex uses to find a file, because we
164 * will use the first extension that matches.
165 * This is only an approximation for the common cases. If we would want to
166 * do it right in all cases, we would need to know which graphics driver is
167 * used and know the extensions of every driver of the graphics package.
169 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
170 "ps.gz", "eps.Z", "ps.Z", 0};
173 * Graphics file extensions known by the pdftex driver of the graphics package.
174 * \sa known_dvips_graphics_formats
176 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
180 * Known file extensions for TeX files as used by \\include.
182 char const * const known_tex_extensions[] = {"tex", 0};
185 /// splits "x=z, y=b" into a map
186 map<string, string> split_map(string const & s)
188 map<string, string> res;
191 for (size_t i = 0; i < v.size(); ++i) {
192 size_t const pos = v[i].find('=');
193 string const index = v[i].substr(0, pos);
194 string const value = v[i].substr(pos + 1, string::npos);
195 res[trim(index)] = trim(value);
202 * Split a LaTeX length into value and unit.
203 * The latter can be a real unit like "pt", or a latex length variable
204 * like "\textwidth". The unit may contain additional stuff like glue
205 * lengths, but we don't care, because such lengths are ERT anyway.
206 * \returns true if \p value and \p unit are valid.
208 bool splitLatexLength(string const & len, string & value, string & unit)
212 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
213 //'4,5' is a valid LaTeX length number. Change it to '4.5'
214 string const length = subst(len, ',', '.');
215 if (i == string::npos)
218 if (len[0] == '\\') {
219 // We had something like \textwidth without a factor
225 value = trim(string(length, 0, i));
229 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
230 if (contains(len, '\\'))
231 unit = trim(string(len, i));
233 unit = lyx::support::lowercase(trim(string(len, i)));
238 /// A simple function to translate a latex length to something lyx can
239 /// understand. Not perfect, but rather best-effort.
240 bool translate_len(string const & length, string & valstring, string & unit)
242 if (!splitLatexLength(length, valstring, unit))
244 // LyX uses percent values
246 istringstream iss(valstring);
251 string const percentval = oss.str();
253 if (unit.empty() || unit[0] != '\\')
255 string::size_type const i = unit.find(' ');
256 string const endlen = (i == string::npos) ? string() : string(unit, i);
257 if (unit == "\\textwidth") {
258 valstring = percentval;
259 unit = "text%" + endlen;
260 } else if (unit == "\\columnwidth") {
261 valstring = percentval;
262 unit = "col%" + endlen;
263 } else if (unit == "\\paperwidth") {
264 valstring = percentval;
265 unit = "page%" + endlen;
266 } else if (unit == "\\linewidth") {
267 valstring = percentval;
268 unit = "line%" + endlen;
269 } else if (unit == "\\paperheight") {
270 valstring = percentval;
271 unit = "pheight%" + endlen;
272 } else if (unit == "\\textheight") {
273 valstring = percentval;
274 unit = "theight%" + endlen;
280 string translate_len(string const & length)
284 if (translate_len(length, value, unit))
286 // If the input is invalid, return what we have.
292 * Translates a LaTeX length into \p value, \p unit and
293 * \p special parts suitable for a box inset.
294 * The difference from translate_len() is that a box inset knows about
295 * some special "units" that are stored in \p special.
297 void translate_box_len(string const & length, string & value, string & unit, string & special)
299 if (translate_len(length, value, unit)) {
300 if (unit == "\\height" || unit == "\\depth" ||
301 unit == "\\totalheight" || unit == "\\width") {
302 special = unit.substr(1);
303 // The unit is not used, but LyX requires a dummy setting
316 * Find a file with basename \p name in path \p path and an extension
319 string find_file(string const & name, string const & path,
320 char const * const * extensions)
322 for (char const * const * what = extensions; *what; ++what) {
323 // We don't use ChangeExtension() because it does the wrong
324 // thing if name contains a dot.
325 string const trial = name + '.' + (*what);
326 if (fs::exists(MakeAbsPath(trial, path)))
333 void begin_inset(ostream & os, string const & name)
335 os << "\n\\begin_inset " << name;
339 void end_inset(ostream & os)
341 os << "\n\\end_inset\n\n";
345 void skip_braces(Parser & p)
347 if (p.next_token().cat() != catBegin)
350 if (p.next_token().cat() == catEnd) {
358 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
361 // We must have a valid layout before outputting the ERT inset.
362 context.check_layout(os);
364 Context newcontext(true, context.textclass);
365 begin_inset(os, "ERT");
366 os << "\nstatus collapsed\n";
367 newcontext.check_layout(os);
368 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
370 os << "\n\\backslash\n";
371 else if (*it == '\n') {
372 newcontext.new_paragraph(os);
373 newcontext.check_layout(os);
377 newcontext.check_end_layout(os);
382 void handle_comment(ostream & os, string const & s, Context & context)
384 // TODO: Handle this better
385 Context newcontext(true, context.textclass);
386 begin_inset(os, "ERT");
387 os << "\nstatus collapsed\n";
388 newcontext.check_layout(os);
389 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
391 os << "\n\\backslash\n";
395 // make sure that our comment is the last thing on the line
396 newcontext.new_paragraph(os);
397 newcontext.check_layout(os);
398 newcontext.check_end_layout(os);
403 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
405 isLayout(string const name) : name_(name) {}
406 bool operator()(LyXLayout_ptr const & ptr) const {
407 return ptr->latexname() == name_;
414 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
417 LyXTextClass::const_iterator beg = textclass.begin();
418 LyXTextClass::const_iterator end = textclass.end();
420 LyXTextClass::const_iterator
421 it = std::find_if(beg, end, isLayout(name));
423 return (it == end) ? LyXLayout_ptr() : *it;
427 void eat_whitespace(Parser &, ostream &, Context &, bool);
430 void output_command_layout(ostream & os, Parser & p, bool outer,
431 Context & parent_context,
432 LyXLayout_ptr newlayout)
434 parent_context.check_end_layout(os);
435 Context context(true, parent_context.textclass, newlayout,
436 parent_context.layout, parent_context.font);
437 if (parent_context.deeper_paragraph) {
438 // We are beginning a nested environment after a
439 // deeper paragraph inside the outer list environment.
440 // Therefore we don't need to output a "begin deeper".
441 context.need_end_deeper = true;
443 context.check_deeper(os);
444 context.check_layout(os);
445 if (context.layout->optionalargs > 0) {
446 eat_whitespace(p, os, context, false);
447 if (p.next_token().character() == '[') {
448 p.get_token(); // eat '['
449 begin_inset(os, "OptArg\n");
450 os << "status collapsed\n\n";
451 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
453 eat_whitespace(p, os, context, false);
456 parse_text(p, os, FLAG_ITEM, outer, context);
457 context.check_end_layout(os);
458 if (parent_context.deeper_paragraph) {
459 // We must suppress the "end deeper" because we
460 // suppressed the "begin deeper" above.
461 context.need_end_deeper = false;
463 context.check_end_deeper(os);
464 // We don't need really a new paragraph, but
465 // we must make sure that the next item gets a \begin_layout.
466 parent_context.new_paragraph(os);
471 * Output a space if necessary.
472 * This function gets called for every whitespace token.
474 * We have three cases here:
475 * 1. A space must be suppressed. Example: The lyxcode case below
476 * 2. A space may be suppressed. Example: Spaces before "\par"
477 * 3. A space must not be suppressed. Example: A space between two words
479 * We currently handle only 1. and 3 and from 2. only the case of
480 * spaces before newlines as a side effect.
482 * 2. could be used to suppress as many spaces as possible. This has two effects:
483 * - Reimporting LyX generated LaTeX files changes almost no whitespace
484 * - Superflous whitespace from non LyX generated LaTeX files is removed.
485 * The drawback is that the logic inside the function becomes
486 * complicated, and that is the reason why it is not implemented.
488 void check_space(Parser const & p, ostream & os, Context & context)
490 Token const next = p.next_token();
491 Token const curr = p.curr_token();
492 // A space before a single newline and vice versa must be ignored
493 // LyX emits a newline before \end{lyxcode}.
494 // This newline must be ignored,
495 // otherwise LyX will add an additional protected space.
496 if (next.cat() == catSpace ||
497 next.cat() == catNewline ||
498 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
501 context.check_layout(os);
507 * Check whether \p command is a known command. If yes,
508 * handle the command with all arguments.
509 * \return true if the command was parsed, false otherwise.
511 bool parse_command(string const & command, Parser & p, ostream & os,
512 bool outer, Context & context)
514 if (known_commands.find(command) != known_commands.end()) {
515 vector<ArgumentType> const & template_arguments = known_commands[command];
516 string ert = command;
517 size_t no_arguments = template_arguments.size();
518 for (size_t i = 0; i < no_arguments; ++i) {
519 switch (template_arguments[i]) {
521 // This argument contains regular LaTeX
522 handle_ert(os, ert + '{', context);
523 parse_text(p, os, FLAG_ITEM, outer, context);
527 // This argument may contain special characters
528 ert += '{' + p.verbatim_item() + '}';
535 handle_ert(os, ert, context);
542 /// Parses a minipage or parbox
543 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
544 Context & parent_context, bool use_parbox)
548 string height_value = "0";
549 string height_unit = "pt";
550 string height_special = "none";
552 if (p.next_token().asInput() == "[") {
553 position = p.getArg('[', ']');
554 if (position != "t" && position != "c" && position != "b") {
556 cerr << "invalid position for minipage/parbox" << endl;
558 if (p.next_token().asInput() == "[") {
559 latex_height = p.getArg('[', ']');
560 translate_box_len(latex_height, height_value, height_unit, height_special);
562 if (p.next_token().asInput() == "[") {
563 inner_pos = p.getArg('[', ']');
564 if (inner_pos != "c" && inner_pos != "t" &&
565 inner_pos != "b" && inner_pos != "s") {
566 inner_pos = position;
567 cerr << "invalid inner_pos for minipage/parbox"
575 string const latex_width = p.verbatim_item();
576 translate_len(latex_width, width_value, width_unit);
577 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
578 // LyX can't handle length variables
583 ss << "\\begin{minipage}";
584 if (!position.empty())
585 ss << '[' << position << ']';
586 if (!latex_height.empty())
587 ss << '[' << latex_height << ']';
588 if (!inner_pos.empty())
589 ss << '[' << inner_pos << ']';
590 ss << "{" << latex_width << "}";
593 handle_ert(os, ss.str(), parent_context);
594 parent_context.new_paragraph(os);
595 parse_text_in_inset(p, os, flags, outer, parent_context);
597 handle_ert(os, "}", parent_context);
599 handle_ert(os, "\\end{minipage}", parent_context);
601 // LyX does not like empty positions, so we have
602 // to set them to the LaTeX default values here.
603 if (position.empty())
605 if (inner_pos.empty())
606 inner_pos = position;
607 parent_context.check_layout(os);
608 begin_inset(os, "Box Frameless\n");
609 os << "position \"" << position << "\"\n";
610 os << "hor_pos \"c\"\n";
611 os << "has_inner_box 1\n";
612 os << "inner_pos \"" << inner_pos << "\"\n";
613 os << "use_parbox " << use_parbox << "\n";
614 os << "width \"" << width_value << width_unit << "\"\n";
615 os << "special \"none\"\n";
616 os << "height \"" << height_value << height_unit << "\"\n";
617 os << "height_special \"" << height_special << "\"\n";
618 os << "status open\n\n";
619 parse_text_in_inset(p, os, flags, outer, parent_context);
621 #ifdef PRESERVE_LAYOUT
622 // lyx puts a % after the end of the minipage
623 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
625 //handle_comment(os, "%dummy", parent_context);
628 parent_context.new_paragraph(os);
630 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
631 //handle_comment(os, "%dummy", parent_context);
634 // We add a protected space if something real follows
635 if (p.good() && p.next_token().cat() != catComment) {
636 os << "\\InsetSpace ~\n";
644 void parse_environment(Parser & p, ostream & os, bool outer,
645 Context & parent_context)
647 LyXLayout_ptr newlayout;
648 string const name = p.getArg('{', '}');
649 const bool is_starred = suffixIs(name, '*');
650 string const unstarred_name = rtrim(name, "*");
651 eat_whitespace(p, os, parent_context, false);
652 active_environments.push_back(name);
654 if (is_math_env(name)) {
655 parent_context.check_layout(os);
656 begin_inset(os, "Formula ");
657 os << "\\begin{" << name << "}";
658 parse_math(p, os, FLAG_END, MATH_MODE);
659 os << "\\end{" << name << "}";
663 else if (name == "tabular" || name == "longtable") {
664 parent_context.check_layout(os);
665 begin_inset(os, "Tabular ");
666 handle_tabular(p, os, name == "longtable", parent_context);
670 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
671 parent_context.check_layout(os);
672 begin_inset(os, "Float " + unstarred_name + "\n");
673 if (p.next_token().asInput() == "[") {
674 os << "placement " << p.getArg('[', ']') << '\n';
676 os << "wide " << convert<string>(is_starred)
677 << "\nsideways false"
678 << "\nstatus open\n\n";
679 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
681 // We don't need really a new paragraph, but
682 // we must make sure that the next item gets a \begin_layout.
683 parent_context.new_paragraph(os);
686 else if (name == "minipage")
687 parse_box(p, os, FLAG_END, outer, parent_context, false);
689 // Alignment settings
690 else if (name == "center" || name == "flushleft" || name == "flushright" ||
691 name == "centering" || name == "raggedright" || name == "raggedleft") {
692 // We must begin a new paragraph if not already done
693 if (! parent_context.atParagraphStart()) {
694 parent_context.check_end_layout(os);
695 parent_context.new_paragraph(os);
697 if (name == "flushleft" || name == "raggedright")
698 parent_context.add_extra_stuff("\\align left\n");
699 else if (name == "flushright" || name == "raggedleft")
700 parent_context.add_extra_stuff("\\align right\n");
702 parent_context.add_extra_stuff("\\align center\n");
703 parse_text(p, os, FLAG_END, outer, parent_context);
704 // Just in case the environment is empty ..
705 parent_context.extra_stuff.erase();
706 // We must begin a new paragraph to reset the alignment
707 parent_context.new_paragraph(os);
710 // The single '=' is meant here.
711 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
712 newlayout->isEnvironment()) {
713 Context context(true, parent_context.textclass, newlayout,
714 parent_context.layout, parent_context.font);
715 if (parent_context.deeper_paragraph) {
716 // We are beginning a nested environment after a
717 // deeper paragraph inside the outer list environment.
718 // Therefore we don't need to output a "begin deeper".
719 context.need_end_deeper = true;
721 parent_context.check_end_layout(os);
722 switch (context.layout->latextype) {
723 case LATEX_LIST_ENVIRONMENT:
724 context.extra_stuff = "\\labelwidthstring "
725 + p.verbatim_item() + '\n';
728 case LATEX_BIB_ENVIRONMENT:
729 p.verbatim_item(); // swallow next arg
735 context.check_deeper(os);
736 parse_text(p, os, FLAG_END, outer, context);
737 context.check_end_layout(os);
738 if (parent_context.deeper_paragraph) {
739 // We must suppress the "end deeper" because we
740 // suppressed the "begin deeper" above.
741 context.need_end_deeper = false;
743 context.check_end_deeper(os);
744 parent_context.new_paragraph(os);
747 else if (name == "appendix") {
748 // This is no good latex style, but it works and is used in some documents...
749 parent_context.check_end_layout(os);
750 Context context(true, parent_context.textclass, parent_context.layout,
751 parent_context.layout, parent_context.font);
752 context.check_layout(os);
753 os << "\\start_of_appendix\n";
754 parse_text(p, os, FLAG_END, outer, context);
755 context.check_end_layout(os);
758 else if (name == "comment") {
759 parent_context.check_layout(os);
760 begin_inset(os, "Note Comment\n");
761 os << "status open\n";
762 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
766 else if (name == "lyxgreyedout") {
767 parent_context.check_layout(os);
768 begin_inset(os, "Note Greyedout\n");
769 os << "status open\n";
770 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
774 else if (name == "tabbing") {
775 // We need to remember that we have to handle '\=' specially
776 handle_ert(os, "\\begin{" + name + "}", parent_context);
777 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
778 handle_ert(os, "\\end{" + name + "}", parent_context);
782 handle_ert(os, "\\begin{" + name + "}", parent_context);
783 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
784 handle_ert(os, "\\end{" + name + "}", parent_context);
787 active_environments.pop_back();
793 /// parses a comment and outputs it to \p os.
794 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
796 BOOST_ASSERT(t.cat() == catComment);
797 if (!t.cs().empty()) {
798 context.check_layout(os);
799 handle_comment(os, '%' + t.cs(), context);
800 if (p.next_token().cat() == catNewline) {
801 // A newline after a comment line starts a new
803 if(!context.atParagraphStart()) {
804 // Only start a new paragraph if not already
805 // done (we might get called recursively)
806 context.new_paragraph(os);
808 eat_whitespace(p, os, context, true);
818 * Reads spaces and comments until the first non-space, non-comment token.
819 * New paragraphs (double newlines or \\par) are handled like simple spaces
820 * if \p eatParagraph is true.
821 * Spaces are skipped, but comments are written to \p os.
823 void eat_whitespace(Parser & p, ostream & os, Context & context,
827 Token const & t = p.get_token();
828 if (t.cat() == catComment)
829 parse_comment(p, os, t, context);
830 else if ((! eatParagraph && p.isParagraph()) ||
831 (t.cat() != catSpace && t.cat() != catNewline)) {
840 * Set a font attribute, parse text and reset the font attribute.
841 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
842 * \param currentvalue Current value of the attribute. Is set to the new
843 * value during parsing.
844 * \param newvalue New value of the attribute
846 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
847 Context & context, string const & attribute,
848 string & currentvalue, string const & newvalue)
850 context.check_layout(os);
851 string oldvalue = currentvalue;
852 currentvalue = newvalue;
853 os << '\n' << attribute << ' ' << newvalue << "\n";
854 parse_text_snippet(p, os, flags, outer, context);
855 currentvalue = oldvalue;
856 os << '\n' << attribute << ' ' << oldvalue << "\n";
860 /// get the arguments of a natbib or jurabib citation command
861 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
863 // We need to distinguish "" and "[]", so we can't use p.getOpt().
865 // text before the citation
867 // text after the citation
868 string after = p.getFullOpt();
870 if (!after.empty()) {
871 before = p.getFullOpt();
872 if (natbibOrder && !before.empty())
873 std::swap(before, after);
875 return std::make_pair(before, after);
879 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
880 string const normalize_filename(string const & name)
882 Parser p(trim(name, "\""));
885 Token const & t = p.get_token();
886 if (t.cat() != catEscape)
888 else if (t.cs() == "lyxdot") {
889 // This is used by LyX for simple dots in relative
893 } else if (t.cs() == "space") {
902 } // anonymous namespace
905 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
908 LyXLayout_ptr newlayout;
909 // Store the latest bibliographystyle (needed for bibtex inset)
910 string bibliographystyle;
911 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
912 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
914 Token const & t = p.get_token();
917 cerr << "t: " << t << " flags: " << flags << "\n";
920 if (flags & FLAG_ITEM) {
921 if (t.cat() == catSpace)
925 if (t.cat() == catBegin) {
926 // skip the brace and collect everything to the next matching
928 flags |= FLAG_BRACE_LAST;
932 // handle only this single token, leave the loop if done
936 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
942 if (t.cat() == catMath) {
943 // we are inside some text mode thingy, so opening new math is allowed
944 context.check_layout(os);
945 begin_inset(os, "Formula ");
946 Token const & n = p.get_token();
947 if (n.cat() == catMath && outer) {
948 // TeX's $$...$$ syntax for displayed math
950 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
952 p.get_token(); // skip the second '$' token
954 // simple $...$ stuff
957 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
963 else if (t.cat() == catSuper || t.cat() == catSub)
964 cerr << "catcode " << t << " illegal in text mode\n";
966 // Basic support for english quotes. This should be
967 // extended to other quotes, but is not so easy (a
968 // left english quote is the same as a right german
970 else if (t.asInput() == "`"
971 && p.next_token().asInput() == "`") {
972 context.check_layout(os);
973 begin_inset(os, "Quotes ");
979 else if (t.asInput() == "'"
980 && p.next_token().asInput() == "'") {
981 context.check_layout(os);
982 begin_inset(os, "Quotes ");
989 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
990 check_space(p, os, context);
992 else if (t.cat() == catLetter ||
993 t.cat() == catOther ||
994 t.cat() == catAlign ||
995 t.cat() == catParameter) {
996 // This translates "&" to "\\&" which may be wrong...
997 context.check_layout(os);
1001 else if (p.isParagraph()) {
1002 context.new_paragraph(os);
1003 eat_whitespace(p, os, context, true);
1006 else if (t.cat() == catActive) {
1007 context.check_layout(os);
1008 if (t.character() == '~') {
1009 if (context.layout->free_spacing)
1012 os << "\\InsetSpace ~\n";
1014 os << t.character();
1017 else if (t.cat() == catBegin) {
1018 context.check_layout(os);
1019 // special handling of font attribute changes
1020 Token const prev = p.prev_token();
1021 Token const next = p.next_token();
1022 Font const oldFont = context.font;
1023 string const s = parse_text(p, FLAG_BRACE_LAST, outer,
1025 context.font = oldFont;
1026 if (s.empty() && (p.next_token().character() == '`' ||
1027 (prev.character() == '-' &&
1028 p.next_token().character() == '-')))
1029 ; // ignore it in {}`` or -{}-
1030 else if (s == "[" || s == "]" || s == "*")
1032 else if (is_known(next.cs(), known_sizes)) {
1033 // s will change the size, so we must reset
1036 if (!context.atParagraphStart())
1038 << context.font.size << "\n";
1039 } else if (is_known(next.cs(), known_font_families)) {
1040 // s will change the font family, so we must
1043 if (!context.atParagraphStart())
1045 << context.font.family << "\n";
1046 } else if (is_known(next.cs(), known_font_series)) {
1047 // s will change the font series, so we must
1050 if (!context.atParagraphStart())
1052 << context.font.series << "\n";
1053 } else if (is_known(next.cs(), known_font_shapes)) {
1054 // s will change the font shape, so we must
1057 if (!context.atParagraphStart())
1059 << context.font.shape << "\n";
1060 } else if (is_known(next.cs(), known_old_font_families) ||
1061 is_known(next.cs(), known_old_font_series) ||
1062 is_known(next.cs(), known_old_font_shapes)) {
1063 // s will change the font family, series
1064 // and shape, so we must reset it here
1066 if (!context.atParagraphStart())
1068 << context.font.family
1070 << context.font.series
1072 << context.font.shape << "\n";
1074 handle_ert(os, "{", context, false);
1075 // s will end the current layout and begin a
1076 // new one if necessary
1078 handle_ert(os, "}", context);
1082 else if (t.cat() == catEnd) {
1083 if (flags & FLAG_BRACE_LAST) {
1086 cerr << "stray '}' in text\n";
1087 handle_ert(os, "}", context);
1090 else if (t.cat() == catComment)
1091 parse_comment(p, os, t, context);
1094 // control sequences
1097 else if (t.cs() == "(") {
1098 context.check_layout(os);
1099 begin_inset(os, "Formula");
1101 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1106 else if (t.cs() == "[") {
1107 context.check_layout(os);
1108 begin_inset(os, "Formula");
1110 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1115 else if (t.cs() == "begin")
1116 parse_environment(p, os, outer, context);
1118 else if (t.cs() == "end") {
1119 if (flags & FLAG_END) {
1120 // eat environment name
1121 string const name = p.getArg('{', '}');
1122 if (name != active_environment())
1123 cerr << "\\end{" + name + "} does not match \\begin{"
1124 + active_environment() + "}\n";
1127 p.error("found 'end' unexpectedly");
1130 else if (t.cs() == "item") {
1133 bool optarg = false;
1134 if (p.next_token().character() == '[') {
1135 p.get_token(); // eat '['
1136 Context newcontext(false, context.textclass);
1137 newcontext.font = context.font;
1138 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1142 context.check_layout(os);
1144 if (context.layout->labeltype != LABEL_MANUAL) {
1145 // lyx does not support \item[\mybullet]
1146 // in itemize environments
1147 handle_ert(os, "[", context);
1149 handle_ert(os, "]", context);
1150 } else if (!s.empty()) {
1151 // The space is needed to separate the
1152 // item from the rest of the sentence.
1154 eat_whitespace(p, os, context, false);
1159 else if (t.cs() == "bibitem") {
1161 context.check_layout(os);
1164 os << '{' << p.verbatim_item() << '}' << "\n";
1167 else if (t.cs() == "def") {
1168 context.check_layout(os);
1169 eat_whitespace(p, os, context, false);
1170 string name = p.get_token().cs();
1171 while (p.next_token().cat() != catBegin)
1172 name += p.get_token().asString();
1173 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1176 else if (t.cs() == "noindent") {
1178 context.add_extra_stuff("\\noindent\n");
1181 else if (t.cs() == "appendix") {
1182 context.add_extra_stuff("\\start_of_appendix\n");
1183 // We need to start a new paragraph. Otherwise the
1184 // appendix in 'bla\appendix\chapter{' would start
1186 context.new_paragraph(os);
1187 // We need to make sure that the paragraph is
1188 // generated even if it is empty. Otherwise the
1189 // appendix in '\par\appendix\par\chapter{' would
1191 context.check_layout(os);
1192 // FIXME: This is a hack to prevent paragraph
1193 // deletion if it is empty. Handle this better!
1195 "%dummy comment inserted by tex2lyx to "
1196 "ensure that this paragraph is not empty",
1198 // Both measures above may generate an additional
1199 // empty paragraph, but that does not hurt, because
1200 // whitespace does not matter here.
1201 eat_whitespace(p, os, context, true);
1204 // Must attempt to parse "Section*" before "Section".
1205 else if ((p.next_token().asInput() == "*") &&
1206 // The single '=' is meant here.
1207 (newlayout = findLayout(context.textclass,
1208 t.cs() + '*')).get() &&
1209 newlayout->isCommand()) {
1211 output_command_layout(os, p, outer, context, newlayout);
1215 // The single '=' is meant here.
1216 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1217 newlayout->isCommand()) {
1218 output_command_layout(os, p, outer, context, newlayout);
1222 else if (t.cs() == "includegraphics") {
1223 bool const clip = p.next_token().asInput() == "*";
1226 map<string, string> opts = split_map(p.getArg('[', ']'));
1228 opts["clip"] = string();
1229 string name = normalize_filename(p.verbatim_item());
1231 string const path = getMasterFilePath();
1232 // We want to preserve relative / absolute filenames,
1233 // therefore path is only used for testing
1234 if (!fs::exists(MakeAbsPath(name, path))) {
1235 // The file extension is probably missing.
1236 // Now try to find it out.
1237 string const dvips_name =
1238 find_file(name, path,
1239 known_dvips_graphics_formats);
1240 string const pdftex_name =
1241 find_file(name, path,
1242 known_pdftex_graphics_formats);
1243 if (!dvips_name.empty()) {
1244 if (!pdftex_name.empty()) {
1245 cerr << "This file contains the "
1247 "\"\\includegraphics{"
1249 "However, files\n\""
1250 << dvips_name << "\" and\n\""
1251 << pdftex_name << "\"\n"
1252 "both exist, so I had to make a "
1253 "choice and took the first one.\n"
1254 "Please move the unwanted one "
1255 "someplace else and try again\n"
1256 "if my choice was wrong."
1260 } else if (!pdftex_name.empty())
1263 if (!fs::exists(MakeAbsPath(name, path)))
1264 cerr << "Warning: Could not find graphics file '"
1265 << name << "'." << endl;
1268 context.check_layout(os);
1269 begin_inset(os, "Graphics ");
1270 os << "\n\tfilename " << name << '\n';
1271 if (opts.find("width") != opts.end())
1273 << translate_len(opts["width"]) << '\n';
1274 if (opts.find("height") != opts.end())
1276 << translate_len(opts["height"]) << '\n';
1277 if (opts.find("scale") != opts.end()) {
1278 istringstream iss(opts["scale"]);
1282 os << "\tscale " << val << '\n';
1284 if (opts.find("angle") != opts.end())
1285 os << "\trotateAngle "
1286 << opts["angle"] << '\n';
1287 if (opts.find("origin") != opts.end()) {
1289 string const opt = opts["origin"];
1290 if (opt.find('l') != string::npos) ss << "left";
1291 if (opt.find('r') != string::npos) ss << "right";
1292 if (opt.find('c') != string::npos) ss << "center";
1293 if (opt.find('t') != string::npos) ss << "Top";
1294 if (opt.find('b') != string::npos) ss << "Bottom";
1295 if (opt.find('B') != string::npos) ss << "Baseline";
1296 if (!ss.str().empty())
1297 os << "\trotateOrigin " << ss.str() << '\n';
1299 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1301 if (opts.find("keepaspectratio") != opts.end())
1302 os << "\tkeepAspectRatio\n";
1303 if (opts.find("clip") != opts.end())
1305 if (opts.find("draft") != opts.end())
1307 if (opts.find("bb") != opts.end())
1308 os << "\tBoundingBox "
1309 << opts["bb"] << '\n';
1310 int numberOfbbOptions = 0;
1311 if (opts.find("bbllx") != opts.end())
1312 numberOfbbOptions++;
1313 if (opts.find("bblly") != opts.end())
1314 numberOfbbOptions++;
1315 if (opts.find("bburx") != opts.end())
1316 numberOfbbOptions++;
1317 if (opts.find("bbury") != opts.end())
1318 numberOfbbOptions++;
1319 if (numberOfbbOptions == 4)
1320 os << "\tBoundingBox "
1321 << opts["bbllx"] << opts["bblly"]
1322 << opts["bburx"] << opts["bbury"] << '\n';
1323 else if (numberOfbbOptions > 0)
1324 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1325 numberOfbbOptions = 0;
1326 if (opts.find("natwidth") != opts.end())
1327 numberOfbbOptions++;
1328 if (opts.find("natheight") != opts.end())
1329 numberOfbbOptions++;
1330 if (numberOfbbOptions == 2)
1331 os << "\tBoundingBox 0bp 0bp "
1332 << opts["natwidth"] << opts["natheight"] << '\n';
1333 else if (numberOfbbOptions > 0)
1334 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1335 ostringstream special;
1336 if (opts.find("hiresbb") != opts.end())
1337 special << "hiresbb,";
1338 if (opts.find("trim") != opts.end())
1340 if (opts.find("viewport") != opts.end())
1341 special << "viewport=" << opts["viewport"] << ',';
1342 if (opts.find("totalheight") != opts.end())
1343 special << "totalheight=" << opts["totalheight"] << ',';
1344 if (opts.find("type") != opts.end())
1345 special << "type=" << opts["type"] << ',';
1346 if (opts.find("ext") != opts.end())
1347 special << "ext=" << opts["ext"] << ',';
1348 if (opts.find("read") != opts.end())
1349 special << "read=" << opts["read"] << ',';
1350 if (opts.find("command") != opts.end())
1351 special << "command=" << opts["command"] << ',';
1352 string s_special = special.str();
1353 if (!s_special.empty()) {
1354 // We had special arguments. Remove the trailing ','.
1355 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1357 // TODO: Handle the unknown settings better.
1358 // Warn about invalid options.
1359 // Check whether some option was given twice.
1363 else if (t.cs() == "footnote" ||
1364 (t.cs() == "thanks" && context.layout->intitle)) {
1366 context.check_layout(os);
1367 begin_inset(os, "Foot\n");
1368 os << "status collapsed\n\n";
1369 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1373 else if (t.cs() == "marginpar") {
1375 context.check_layout(os);
1376 begin_inset(os, "Marginal\n");
1377 os << "status collapsed\n\n";
1378 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1382 else if (t.cs() == "ensuremath") {
1384 context.check_layout(os);
1385 Context newcontext(false, context.textclass);
1386 newcontext.font = context.font;
1387 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1388 if (s == "±" || s == "³" || s == "²" || s == "µ")
1391 handle_ert(os, "\\ensuremath{" + s + "}",
1395 else if (t.cs() == "hfill") {
1396 context.check_layout(os);
1397 os << "\n\\hfill\n";
1402 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1403 // FIXME: Somehow prevent title layouts if
1404 // "maketitle" was not found
1406 skip_braces(p); // swallow this
1409 else if (t.cs() == "tableofcontents") {
1411 context.check_layout(os);
1412 begin_inset(os, "LatexCommand \\tableofcontents\n");
1414 skip_braces(p); // swallow this
1417 else if (t.cs() == "listoffigures") {
1419 context.check_layout(os);
1420 begin_inset(os, "FloatList figure\n");
1422 skip_braces(p); // swallow this
1425 else if (t.cs() == "listoftables") {
1427 context.check_layout(os);
1428 begin_inset(os, "FloatList table\n");
1430 skip_braces(p); // swallow this
1433 else if (t.cs() == "listof") {
1434 p.skip_spaces(true);
1435 string const name = p.get_token().asString();
1436 if (context.textclass.floats().typeExist(name)) {
1437 context.check_layout(os);
1438 begin_inset(os, "FloatList ");
1441 p.get_token(); // swallow second arg
1443 handle_ert(os, "\\listof{" + name + "}", context);
1446 else if (t.cs() == "textrm")
1447 parse_text_attributes(p, os, FLAG_ITEM, outer,
1448 context, "\\family",
1449 context.font.family, "roman");
1451 else if (t.cs() == "textsf")
1452 parse_text_attributes(p, os, FLAG_ITEM, outer,
1453 context, "\\family",
1454 context.font.family, "sans");
1456 else if (t.cs() == "texttt")
1457 parse_text_attributes(p, os, FLAG_ITEM, outer,
1458 context, "\\family",
1459 context.font.family, "typewriter");
1461 else if (t.cs() == "textmd")
1462 parse_text_attributes(p, os, FLAG_ITEM, outer,
1463 context, "\\series",
1464 context.font.series, "medium");
1466 else if (t.cs() == "textbf")
1467 parse_text_attributes(p, os, FLAG_ITEM, outer,
1468 context, "\\series",
1469 context.font.series, "bold");
1471 else if (t.cs() == "textup")
1472 parse_text_attributes(p, os, FLAG_ITEM, outer,
1474 context.font.shape, "up");
1476 else if (t.cs() == "textit")
1477 parse_text_attributes(p, os, FLAG_ITEM, outer,
1479 context.font.shape, "italic");
1481 else if (t.cs() == "textsl")
1482 parse_text_attributes(p, os, FLAG_ITEM, outer,
1484 context.font.shape, "slanted");
1486 else if (t.cs() == "textsc")
1487 parse_text_attributes(p, os, FLAG_ITEM, outer,
1489 context.font.shape, "smallcaps");
1491 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1492 context.check_layout(os);
1493 Font oldFont = context.font;
1494 context.font.init();
1495 context.font.size = oldFont.size;
1496 os << "\n\\family " << context.font.family << "\n";
1497 os << "\n\\series " << context.font.series << "\n";
1498 os << "\n\\shape " << context.font.shape << "\n";
1499 if (t.cs() == "textnormal") {
1500 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1501 context.font = oldFont;
1502 os << "\n\\shape " << oldFont.shape << "\n";
1503 os << "\n\\series " << oldFont.series << "\n";
1504 os << "\n\\family " << oldFont.family << "\n";
1506 eat_whitespace(p, os, context, false);
1509 else if (t.cs() == "underbar") {
1510 // Do NOT handle \underline.
1511 // \underbar cuts through y, g, q, p etc.,
1512 // \underline does not.
1513 context.check_layout(os);
1514 os << "\n\\bar under\n";
1515 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1516 os << "\n\\bar default\n";
1519 else if (t.cs() == "emph" || t.cs() == "noun") {
1520 context.check_layout(os);
1521 os << "\n\\" << t.cs() << " on\n";
1522 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1523 os << "\n\\" << t.cs() << " default\n";
1526 else if (use_natbib &&
1527 is_known(t.cs(), known_natbib_commands) &&
1528 ((t.cs() != "citefullauthor" &&
1529 t.cs() != "citeyear" &&
1530 t.cs() != "citeyearpar") ||
1531 p.next_token().asInput() != "*")) {
1532 context.check_layout(os);
1534 // \citet[before][after]{a} \citet[after][before]{a}
1535 // \citet[before][]{a} \citet[][before]{a}
1536 // \citet[after]{a} \citet[after]{a}
1537 // \citet{a} \citet{a}
1538 string command = '\\' + t.cs();
1539 if (p.next_token().asInput() == "*") {
1543 if (command == "\\citefullauthor")
1544 // alternative name for "\\citeauthor*"
1545 command = "\\citeauthor*";
1547 // text before the citation
1549 // text after the citation
1552 boost::tie(before, after) = getCiteArguments(p, true);
1553 if (command == "\\cite") {
1554 // \cite without optional argument means
1555 // \citet, \cite with at least one optional
1556 // argument means \citep.
1557 if (before.empty() && after.empty())
1558 command = "\\citet";
1560 command = "\\citep";
1562 if (before.empty() && after == "[]")
1563 // avoid \citet[]{a}
1565 else if (before == "[]" && after == "[]") {
1566 // avoid \citet[][]{a}
1570 begin_inset(os, "LatexCommand ");
1571 os << command << after << before
1572 << '{' << p.verbatim_item() << "}\n";
1576 else if (use_jurabib &&
1577 is_known(t.cs(), known_jurabib_commands)) {
1578 context.check_layout(os);
1579 string const command = '\\' + t.cs();
1580 char argumentOrder = '\0';
1581 vector<string> const & options = used_packages["jurabib"];
1582 if (std::find(options.begin(), options.end(),
1583 "natbiborder") != options.end())
1584 argumentOrder = 'n';
1585 else if (std::find(options.begin(), options.end(),
1586 "jurabiborder") != options.end())
1587 argumentOrder = 'j';
1589 // text before the citation
1591 // text after the citation
1594 boost::tie(before, after) =
1595 getCiteArguments(p, argumentOrder != 'j');
1596 string const citation = p.verbatim_item();
1597 if (!before.empty() && argumentOrder == '\0') {
1598 cerr << "Warning: Assuming argument order "
1599 "of jurabib version 0.6 for\n'"
1600 << command << before << after << '{'
1601 << citation << "}'.\n"
1602 "Add 'jurabiborder' to the jurabib "
1603 "package options if you used an\n"
1604 "earlier jurabib version." << endl;
1606 begin_inset(os, "LatexCommand ");
1607 os << command << after << before
1608 << '{' << citation << "}\n";
1612 else if (is_known(t.cs(), known_latex_commands)) {
1613 // This needs to be after the check for natbib and
1614 // jurabib commands, because "cite" has different
1615 // arguments with natbib and jurabib.
1616 context.check_layout(os);
1617 begin_inset(os, "LatexCommand ");
1618 os << '\\' << t.cs();
1619 // lyx cannot handle newlines in a latex command
1620 // FIXME: Move the substitution into parser::getOpt()?
1621 os << subst(p.getOpt(), "\n", " ");
1622 os << subst(p.getOpt(), "\n", " ");
1623 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1627 else if (is_known(t.cs(), known_quotes)) {
1628 char const * const * where = is_known(t.cs(), known_quotes);
1629 context.check_layout(os);
1630 begin_inset(os, "Quotes ");
1631 os << known_coded_quotes[where - known_quotes];
1633 // LyX adds {} after the quote, so we have to eat
1634 // spaces here if there are any before a possible
1636 eat_whitespace(p, os, context, false);
1640 else if (is_known(t.cs(), known_sizes)) {
1641 char const * const * where = is_known(t.cs(), known_sizes);
1642 context.check_layout(os);
1643 context.font.size = known_coded_sizes[where - known_sizes];
1644 os << "\n\\size " << context.font.size << '\n';
1645 eat_whitespace(p, os, context, false);
1648 else if (is_known(t.cs(), known_font_families)) {
1649 char const * const * where =
1650 is_known(t.cs(), known_font_families);
1651 context.check_layout(os);
1652 context.font.family =
1653 known_coded_font_families[where - known_font_families];
1654 os << "\n\\family " << context.font.family << '\n';
1655 eat_whitespace(p, os, context, false);
1658 else if (is_known(t.cs(), known_font_series)) {
1659 char const * const * where =
1660 is_known(t.cs(), known_font_series);
1661 context.check_layout(os);
1662 context.font.series =
1663 known_coded_font_series[where - known_font_series];
1664 os << "\n\\series " << context.font.series << '\n';
1665 eat_whitespace(p, os, context, false);
1668 else if (is_known(t.cs(), known_font_shapes)) {
1669 char const * const * where =
1670 is_known(t.cs(), known_font_shapes);
1671 context.check_layout(os);
1672 context.font.shape =
1673 known_coded_font_shapes[where - known_font_shapes];
1674 os << "\n\\shape " << context.font.shape << '\n';
1675 eat_whitespace(p, os, context, false);
1677 else if (is_known(t.cs(), known_old_font_families)) {
1678 char const * const * where =
1679 is_known(t.cs(), known_old_font_families);
1680 context.check_layout(os);
1681 string oldsize = context.font.size;
1682 context.font.init();
1683 context.font.size = oldsize;
1684 context.font.family =
1685 known_coded_font_families[where - known_old_font_families];
1686 os << "\n\\family " << context.font.family << "\n"
1687 << "\\series " << context.font.series << "\n"
1688 << "\\shape " << context.font.shape << "\n";
1689 eat_whitespace(p, os, context, false);
1692 else if (is_known(t.cs(), known_old_font_series)) {
1693 char const * const * where =
1694 is_known(t.cs(), known_old_font_series);
1695 context.check_layout(os);
1696 string oldsize = context.font.size;
1697 context.font.init();
1698 context.font.size = oldsize;
1699 context.font.series =
1700 known_coded_font_series[where - known_old_font_series];
1701 os << "\n\\family " << context.font.family << "\n"
1702 << "\\series " << context.font.series << "\n"
1703 << "\\shape " << context.font.shape << "\n";
1704 eat_whitespace(p, os, context, false);
1707 else if (is_known(t.cs(), known_old_font_shapes)) {
1708 char const * const * where =
1709 is_known(t.cs(), known_old_font_shapes);
1710 context.check_layout(os);
1711 string oldsize = context.font.size;
1712 context.font.init();
1713 context.font.size = oldsize;
1714 context.font.shape =
1715 known_coded_font_shapes[where - known_old_font_shapes];
1716 os << "\n\\family " << context.font.family << "\n"
1717 << "\\series " << context.font.series << "\n"
1718 << "\\shape " << context.font.shape << "\n";
1719 eat_whitespace(p, os, context, false);
1722 else if (t.cs() == "LyX" || t.cs() == "TeX"
1723 || t.cs() == "LaTeX") {
1724 context.check_layout(os);
1726 skip_braces(p); // eat {}
1729 else if (t.cs() == "LaTeXe") {
1730 context.check_layout(os);
1732 skip_braces(p); // eat {}
1735 else if (t.cs() == "ldots") {
1736 context.check_layout(os);
1738 os << "\\SpecialChar \\ldots{}\n";
1741 else if (t.cs() == "lyxarrow") {
1742 context.check_layout(os);
1743 os << "\\SpecialChar \\menuseparator\n";
1747 else if (t.cs() == "textcompwordmark") {
1748 context.check_layout(os);
1749 os << "\\SpecialChar \\textcompwordmark{}\n";
1753 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1754 context.check_layout(os);
1755 os << "\\SpecialChar \\@.\n";
1759 else if (t.cs() == "-") {
1760 context.check_layout(os);
1761 os << "\\SpecialChar \\-\n";
1764 else if (t.cs() == "textasciitilde") {
1765 context.check_layout(os);
1770 else if (t.cs() == "textasciicircum") {
1771 context.check_layout(os);
1776 else if (t.cs() == "textbackslash") {
1777 context.check_layout(os);
1778 os << "\n\\backslash\n";
1782 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1783 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1785 context.check_layout(os);
1789 else if (t.cs() == "char") {
1790 context.check_layout(os);
1791 if (p.next_token().character() == '`') {
1793 if (p.next_token().cs() == "\"") {
1798 handle_ert(os, "\\char`", context);
1801 handle_ert(os, "\\char", context);
1805 else if (t.cs() == "\"") {
1806 context.check_layout(os);
1807 string const name = p.verbatim_item();
1808 if (name == "a") os << 'ä';
1809 else if (name == "o") os << 'ö';
1810 else if (name == "u") os << 'ü';
1811 else if (name == "A") os << 'Ä';
1812 else if (name == "O") os << 'Ö';
1813 else if (name == "U") os << 'Ü';
1814 else handle_ert(os, "\"{" + name + "}", context);
1817 // Problem: \= creates a tabstop inside the tabbing environment
1818 // and else an accent. In the latter case we really would want
1819 // \={o} instead of \= o.
1820 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1821 handle_ert(os, t.asInput(), context);
1823 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1824 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1825 // we need the trim as the LyX parser chokes on such spaces
1826 context.check_layout(os);
1827 os << "\n\\i \\" << t.cs() << "{"
1828 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1831 else if (t.cs() == "ss") {
1832 context.check_layout(os);
1836 else if (t.cs() == "i" || t.cs() == "j") {
1837 context.check_layout(os);
1838 os << "\\" << t.cs() << ' ';
1841 else if (t.cs() == "\\") {
1842 context.check_layout(os);
1843 string const next = p.next_token().asInput();
1845 handle_ert(os, "\\\\" + p.getOpt(), context);
1846 else if (next == "*") {
1848 handle_ert(os, "\\\\*" + p.getOpt(), context);
1851 os << "\n\\newline\n";
1855 else if (t.cs() == "input" || t.cs() == "include"
1856 || t.cs() == "verbatiminput") {
1857 string name = '\\' + t.cs();
1858 if (t.cs() == "verbatiminput"
1859 && p.next_token().asInput() == "*")
1860 name += p.get_token().asInput();
1861 context.check_layout(os);
1862 begin_inset(os, "Include ");
1863 string filename(normalize_filename(p.getArg('{', '}')));
1864 string const path = getMasterFilePath();
1865 // We want to preserve relative / absolute filenames,
1866 // therefore path is only used for testing
1867 if (t.cs() == "include" &&
1868 !fs::exists(MakeAbsPath(filename, path))) {
1869 // The file extension is probably missing.
1870 // Now try to find it out.
1871 string const tex_name =
1872 find_file(filename, path,
1873 known_tex_extensions);
1874 if (!tex_name.empty())
1875 filename = tex_name;
1877 if (fs::exists(MakeAbsPath(filename, path))) {
1878 string const abstexname =
1879 MakeAbsPath(filename, path);
1880 string const abslyxname =
1881 ChangeExtension(abstexname, ".lyx");
1882 string const lyxname =
1883 ChangeExtension(filename, ".lyx");
1884 if (t.cs() != "verbatiminput" &&
1885 tex2lyx(abstexname, abslyxname)) {
1886 os << name << '{' << lyxname << "}\n";
1888 os << name << '{' << filename << "}\n";
1891 cerr << "Warning: Could not find included file '"
1892 << filename << "'." << endl;
1893 os << name << '{' << filename << "}\n";
1895 os << "preview false\n";
1899 else if (t.cs() == "fancyhead") {
1900 context.check_layout(os);
1902 ss << "\\fancyhead";
1904 ss << '{' << p.verbatim_item() << "}\n";
1905 handle_ert(os, ss.str(), context);
1908 else if (t.cs() == "bibliographystyle") {
1909 // store new bibliographystyle
1910 bibliographystyle = p.verbatim_item();
1911 // output new bibliographystyle.
1912 // This is only necessary if used in some other macro than \bibliography.
1913 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1916 else if (t.cs() == "bibliography") {
1917 context.check_layout(os);
1918 begin_inset(os, "LatexCommand ");
1920 // Do we have a bibliographystyle set?
1921 if (!bibliographystyle.empty()) {
1922 os << '[' << bibliographystyle << ']';
1924 os << '{' << p.verbatim_item() << "}\n";
1928 else if (t.cs() == "parbox")
1929 parse_box(p, os, FLAG_ITEM, outer, context, true);
1931 else if (t.cs() == "smallskip" ||
1932 t.cs() == "medskip" ||
1933 t.cs() == "bigskip" ||
1934 t.cs() == "vfill") {
1935 context.check_layout(os);
1936 begin_inset(os, "VSpace ");
1942 else if (t.cs() == "newcommand" ||
1943 t.cs() == "providecommand" ||
1944 t.cs() == "renewcommand") {
1945 // these could be handled by parse_command(), but
1946 // we need to call add_known_command() here.
1947 string name = t.asInput();
1948 if (p.next_token().asInput() == "*") {
1949 // Starred form. Eat '*'
1953 string const command = p.verbatim_item();
1954 string const opt1 = p.getOpt();
1955 string const opt2 = p.getFullOpt();
1956 add_known_command(command, opt1, !opt2.empty());
1957 string const ert = name + '{' + command + '}' +
1959 '{' + p.verbatim_item() + '}';
1960 handle_ert(os, ert, context);
1963 else if (t.cs() == "vspace") {
1964 bool starred = false;
1965 if (p.next_token().asInput() == "*") {
1969 string const length = p.verbatim_item();
1972 bool valid = splitLatexLength(length, valstring, unit);
1973 bool known_vspace = false;
1974 bool known_unit = false;
1977 istringstream iss(valstring);
1980 if (unit == "\\smallskipamount") {
1982 known_vspace = true;
1983 } else if (unit == "\\medskipamount") {
1985 known_vspace = true;
1986 } else if (unit == "\\bigskipamount") {
1988 known_vspace = true;
1989 } else if (unit == "\\fill") {
1991 known_vspace = true;
1994 if (!known_vspace) {
1995 switch (unitFromString(unit)) {
2016 if (known_unit || known_vspace) {
2017 // Literal length or known variable
2018 context.check_layout(os);
2019 begin_inset(os, "VSpace ");
2027 // LyX can't handle other length variables in Inset VSpace
2028 string name = t.asInput();
2033 handle_ert(os, name + '{' + unit + '}', context);
2034 else if (value == -1.0)
2035 handle_ert(os, name + "{-" + unit + '}', context);
2037 handle_ert(os, name + '{' + valstring + unit + '}', context);
2039 handle_ert(os, name + '{' + length + '}', context);
2044 //cerr << "#: " << t << " mode: " << mode << endl;
2045 // heuristic: read up to next non-nested space
2047 string s = t.asInput();
2048 string z = p.verbatim_item();
2049 while (p.good() && z != " " && z.size()) {
2050 //cerr << "read: " << z << endl;
2052 z = p.verbatim_item();
2054 cerr << "found ERT: " << s << endl;
2055 handle_ert(os, s + ' ', context);
2057 string name = t.asInput();
2058 if (p.next_token().asInput() == "*") {
2059 // Starred commands like \vspace*{}
2060 p.get_token(); // Eat '*'
2063 if (! parse_command(name, p, os, outer, context))
2064 handle_ert(os, name, context);
2067 if (flags & FLAG_LEAVE) {
2068 flags &= ~FLAG_LEAVE;