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();
792 /// parses a comment and outputs it to \p os.
793 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
795 BOOST_ASSERT(t.cat() == catComment);
796 context.check_layout(os);
797 if (!t.cs().empty()) {
798 handle_comment(os, '%' + t.cs(), context);
799 if (p.next_token().cat() == catNewline) {
800 // A newline after a comment line starts a new
802 if(!context.atParagraphStart()) {
803 // Only start a new paragraph if not already
804 // done (we might get called recursively)
805 context.new_paragraph(os);
807 eat_whitespace(p, os, context, true);
817 * Reads spaces and comments until the first non-space, non-comment token.
818 * New paragraphs (double newlines or \\par) are handled like simple spaces
819 * if \p eatParagraph is true.
820 * Spaces are skipped, but comments are written to \p os.
822 void eat_whitespace(Parser & p, ostream & os, Context & context,
826 Token const & t = p.get_token();
827 if (t.cat() == catComment)
828 parse_comment(p, os, t, context);
829 else if ((! eatParagraph && p.isParagraph()) ||
830 (t.cat() != catSpace && t.cat() != catNewline)) {
839 * Set a font attribute, parse text and reset the font attribute.
840 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
841 * \param currentvalue Current value of the attribute. Is set to the new
842 * value during parsing.
843 * \param newvalue New value of the attribute
845 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
846 Context & context, string const & attribute,
847 string & currentvalue, string const & newvalue)
849 context.check_layout(os);
850 string oldvalue = currentvalue;
851 currentvalue = newvalue;
852 os << '\n' << attribute << ' ' << newvalue << "\n";
853 parse_text_snippet(p, os, flags, outer, context);
854 currentvalue = oldvalue;
855 os << '\n' << attribute << ' ' << oldvalue << "\n";
859 /// get the arguments of a natbib or jurabib citation command
860 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
862 // We need to distinguish "" and "[]", so we can't use p.getOpt().
864 // text before the citation
866 // text after the citation
867 string after = p.getFullOpt();
869 if (!after.empty()) {
870 before = p.getFullOpt();
871 if (natbibOrder && !before.empty())
872 std::swap(before, after);
874 return std::make_pair(before, after);
878 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
879 string const normalize_filename(string const & name)
881 Parser p(trim(name, "\""));
884 Token const & t = p.get_token();
885 if (t.cat() != catEscape)
887 else if (t.cs() == "lyxdot") {
888 // This is used by LyX for simple dots in relative
892 } else if (t.cs() == "space") {
901 } // anonymous namespace
904 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
907 LyXLayout_ptr newlayout;
908 // Store the latest bibliographystyle (needed for bibtex inset)
909 string bibliographystyle;
910 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
911 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
913 Token const & t = p.get_token();
916 cerr << "t: " << t << " flags: " << flags << "\n";
919 if (flags & FLAG_ITEM) {
920 if (t.cat() == catSpace)
924 if (t.cat() == catBegin) {
925 // skip the brace and collect everything to the next matching
927 flags |= FLAG_BRACE_LAST;
931 // handle only this single token, leave the loop if done
935 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
941 if (t.cat() == catMath) {
942 // we are inside some text mode thingy, so opening new math is allowed
943 context.check_layout(os);
944 begin_inset(os, "Formula ");
945 Token const & n = p.get_token();
946 if (n.cat() == catMath && outer) {
947 // TeX's $$...$$ syntax for displayed math
949 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
951 p.get_token(); // skip the second '$' token
953 // simple $...$ stuff
956 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
962 else if (t.cat() == catSuper || t.cat() == catSub)
963 cerr << "catcode " << t << " illegal in text mode\n";
965 // Basic support for english quotes. This should be
966 // extended to other quotes, but is not so easy (a
967 // left english quote is the same as a right german
969 else if (t.asInput() == "`"
970 && p.next_token().asInput() == "`") {
971 context.check_layout(os);
972 begin_inset(os, "Quotes ");
978 else if (t.asInput() == "'"
979 && p.next_token().asInput() == "'") {
980 context.check_layout(os);
981 begin_inset(os, "Quotes ");
988 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
989 check_space(p, os, context);
991 else if (t.cat() == catLetter ||
992 t.cat() == catOther ||
993 t.cat() == catAlign ||
994 t.cat() == catParameter) {
995 // This translates "&" to "\\&" which may be wrong...
996 context.check_layout(os);
1000 else if (p.isParagraph()) {
1001 context.new_paragraph(os);
1002 eat_whitespace(p, os, context, true);
1005 else if (t.cat() == catActive) {
1006 context.check_layout(os);
1007 if (t.character() == '~') {
1008 if (context.layout->free_spacing)
1011 os << "\\InsetSpace ~\n";
1013 os << t.character();
1016 else if (t.cat() == catBegin) {
1017 context.check_layout(os);
1018 // special handling of font attribute changes
1019 Token const prev = p.prev_token();
1020 Token const next = p.next_token();
1021 Font const oldFont = context.font;
1022 string const s = parse_text(p, FLAG_BRACE_LAST, outer,
1024 context.font = oldFont;
1025 if (s.empty() && (p.next_token().character() == '`' ||
1026 (prev.character() == '-' &&
1027 p.next_token().character() == '-')))
1028 ; // ignore it in {}`` or -{}-
1029 else if (s == "[" || s == "]" || s == "*")
1031 else if (is_known(next.cs(), known_sizes)) {
1032 // s will change the size, so we must reset
1035 if (!context.atParagraphStart())
1037 << context.font.size << "\n";
1038 } else if (is_known(next.cs(), known_font_families)) {
1039 // s will change the font family, so we must
1042 if (!context.atParagraphStart())
1044 << context.font.family << "\n";
1045 } else if (is_known(next.cs(), known_font_series)) {
1046 // s will change the font series, so we must
1049 if (!context.atParagraphStart())
1051 << context.font.series << "\n";
1052 } else if (is_known(next.cs(), known_font_shapes)) {
1053 // s will change the font shape, so we must
1056 if (!context.atParagraphStart())
1058 << context.font.shape << "\n";
1059 } else if (is_known(next.cs(), known_old_font_families) ||
1060 is_known(next.cs(), known_old_font_series) ||
1061 is_known(next.cs(), known_old_font_shapes)) {
1062 // s will change the font family, series
1063 // and shape, so we must reset it here
1065 if (!context.atParagraphStart())
1067 << context.font.family
1069 << context.font.series
1071 << context.font.shape << "\n";
1073 handle_ert(os, "{", context, false);
1074 // s will end the current layout and begin a
1075 // new one if necessary
1077 handle_ert(os, "}", context);
1081 else if (t.cat() == catEnd) {
1082 if (flags & FLAG_BRACE_LAST) {
1085 cerr << "stray '}' in text\n";
1086 handle_ert(os, "}", context);
1089 else if (t.cat() == catComment)
1090 parse_comment(p, os, t, context);
1093 // control sequences
1096 else if (t.cs() == "(") {
1097 context.check_layout(os);
1098 begin_inset(os, "Formula");
1100 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1105 else if (t.cs() == "[") {
1106 context.check_layout(os);
1107 begin_inset(os, "Formula");
1109 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1114 else if (t.cs() == "begin")
1115 parse_environment(p, os, outer, context);
1117 else if (t.cs() == "end") {
1118 if (flags & FLAG_END) {
1119 // eat environment name
1120 string const name = p.getArg('{', '}');
1121 if (name != active_environment())
1122 cerr << "\\end{" + name + "} does not match \\begin{"
1123 + active_environment() + "}\n";
1126 p.error("found 'end' unexpectedly");
1129 else if (t.cs() == "item") {
1132 bool optarg = false;
1133 if (p.next_token().character() == '[') {
1134 p.get_token(); // eat '['
1135 Context newcontext(false, context.textclass);
1136 newcontext.font = context.font;
1137 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1141 context.check_layout(os);
1143 if (context.layout->labeltype != LABEL_MANUAL) {
1144 // lyx does not support \item[\mybullet]
1145 // in itemize environments
1146 handle_ert(os, "[", context);
1148 handle_ert(os, "]", context);
1149 } else if (!s.empty()) {
1150 // The space is needed to separate the
1151 // item from the rest of the sentence.
1153 eat_whitespace(p, os, context, false);
1158 else if (t.cs() == "bibitem") {
1160 context.check_layout(os);
1163 os << '{' << p.verbatim_item() << '}' << "\n";
1166 else if (t.cs() == "def") {
1167 context.check_layout(os);
1168 eat_whitespace(p, os, context, false);
1169 string name = p.get_token().cs();
1170 while (p.next_token().cat() != catBegin)
1171 name += p.get_token().asString();
1172 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1175 else if (t.cs() == "noindent") {
1177 context.add_extra_stuff("\\noindent\n");
1180 else if (t.cs() == "appendix") {
1181 context.add_extra_stuff("\\start_of_appendix\n");
1182 // We need to start a new paragraph. Otherwise the
1183 // appendix in 'bla\appendix\chapter{' would start
1185 context.new_paragraph(os);
1186 // We need to make sure that the paragraph is
1187 // generated even if it is empty. Otherwise the
1188 // appendix in '\par\appendix\par\chapter{' would
1190 context.check_layout(os);
1191 // FIXME: This is a hack to prevent paragraph
1192 // deletion if it is empty. Handle this better!
1194 "%dummy comment inserted by tex2lyx to "
1195 "ensure that this paragraph is not empty",
1197 // Both measures above may generate an additional
1198 // empty paragraph, but that does not hurt, because
1199 // whitespace does not matter here.
1200 eat_whitespace(p, os, context, true);
1203 // Must attempt to parse "Section*" before "Section".
1204 else if ((p.next_token().asInput() == "*") &&
1205 // The single '=' is meant here.
1206 (newlayout = findLayout(context.textclass,
1207 t.cs() + '*')).get() &&
1208 newlayout->isCommand()) {
1210 output_command_layout(os, p, outer, context, newlayout);
1214 // The single '=' is meant here.
1215 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1216 newlayout->isCommand()) {
1217 output_command_layout(os, p, outer, context, newlayout);
1221 else if (t.cs() == "includegraphics") {
1222 bool const clip = p.next_token().asInput() == "*";
1225 map<string, string> opts = split_map(p.getArg('[', ']'));
1227 opts["clip"] = string();
1228 string name = normalize_filename(p.verbatim_item());
1230 string const path = getMasterFilePath();
1231 // We want to preserve relative / absolute filenames,
1232 // therefore path is only used for testing
1233 if (!fs::exists(MakeAbsPath(name, path))) {
1234 // The file extension is probably missing.
1235 // Now try to find it out.
1236 string const dvips_name =
1237 find_file(name, path,
1238 known_dvips_graphics_formats);
1239 string const pdftex_name =
1240 find_file(name, path,
1241 known_pdftex_graphics_formats);
1242 if (!dvips_name.empty()) {
1243 if (!pdftex_name.empty()) {
1244 cerr << "This file contains the "
1246 "\"\\includegraphics{"
1248 "However, files\n\""
1249 << dvips_name << "\" and\n\""
1250 << pdftex_name << "\"\n"
1251 "both exist, so I had to make a "
1252 "choice and took the first one.\n"
1253 "Please move the unwanted one "
1254 "someplace else and try again\n"
1255 "if my choice was wrong."
1259 } else if (!pdftex_name.empty())
1262 if (!fs::exists(MakeAbsPath(name, path)))
1263 cerr << "Warning: Could not find graphics file '"
1264 << name << "'." << endl;
1267 context.check_layout(os);
1268 begin_inset(os, "Graphics ");
1269 os << "\n\tfilename " << name << '\n';
1270 if (opts.find("width") != opts.end())
1272 << translate_len(opts["width"]) << '\n';
1273 if (opts.find("height") != opts.end())
1275 << translate_len(opts["height"]) << '\n';
1276 if (opts.find("scale") != opts.end()) {
1277 istringstream iss(opts["scale"]);
1281 os << "\tscale " << val << '\n';
1283 if (opts.find("angle") != opts.end())
1284 os << "\trotateAngle "
1285 << opts["angle"] << '\n';
1286 if (opts.find("origin") != opts.end()) {
1288 string const opt = opts["origin"];
1289 if (opt.find('l') != string::npos) ss << "left";
1290 if (opt.find('r') != string::npos) ss << "right";
1291 if (opt.find('c') != string::npos) ss << "center";
1292 if (opt.find('t') != string::npos) ss << "Top";
1293 if (opt.find('b') != string::npos) ss << "Bottom";
1294 if (opt.find('B') != string::npos) ss << "Baseline";
1295 if (!ss.str().empty())
1296 os << "\trotateOrigin " << ss.str() << '\n';
1298 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1300 if (opts.find("keepaspectratio") != opts.end())
1301 os << "\tkeepAspectRatio\n";
1302 if (opts.find("clip") != opts.end())
1304 if (opts.find("draft") != opts.end())
1306 if (opts.find("bb") != opts.end())
1307 os << "\tBoundingBox "
1308 << opts["bb"] << '\n';
1309 int numberOfbbOptions = 0;
1310 if (opts.find("bbllx") != opts.end())
1311 numberOfbbOptions++;
1312 if (opts.find("bblly") != opts.end())
1313 numberOfbbOptions++;
1314 if (opts.find("bburx") != opts.end())
1315 numberOfbbOptions++;
1316 if (opts.find("bbury") != opts.end())
1317 numberOfbbOptions++;
1318 if (numberOfbbOptions == 4)
1319 os << "\tBoundingBox "
1320 << opts["bbllx"] << opts["bblly"]
1321 << opts["bburx"] << opts["bbury"] << '\n';
1322 else if (numberOfbbOptions > 0)
1323 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1324 numberOfbbOptions = 0;
1325 if (opts.find("natwidth") != opts.end())
1326 numberOfbbOptions++;
1327 if (opts.find("natheight") != opts.end())
1328 numberOfbbOptions++;
1329 if (numberOfbbOptions == 2)
1330 os << "\tBoundingBox 0bp 0bp "
1331 << opts["natwidth"] << opts["natheight"] << '\n';
1332 else if (numberOfbbOptions > 0)
1333 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1334 ostringstream special;
1335 if (opts.find("hiresbb") != opts.end())
1336 special << "hiresbb,";
1337 if (opts.find("trim") != opts.end())
1339 if (opts.find("viewport") != opts.end())
1340 special << "viewport=" << opts["viewport"] << ',';
1341 if (opts.find("totalheight") != opts.end())
1342 special << "totalheight=" << opts["totalheight"] << ',';
1343 if (opts.find("type") != opts.end())
1344 special << "type=" << opts["type"] << ',';
1345 if (opts.find("ext") != opts.end())
1346 special << "ext=" << opts["ext"] << ',';
1347 if (opts.find("read") != opts.end())
1348 special << "read=" << opts["read"] << ',';
1349 if (opts.find("command") != opts.end())
1350 special << "command=" << opts["command"] << ',';
1351 string s_special = special.str();
1352 if (!s_special.empty()) {
1353 // We had special arguments. Remove the trailing ','.
1354 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1356 // TODO: Handle the unknown settings better.
1357 // Warn about invalid options.
1358 // Check whether some option was given twice.
1362 else if (t.cs() == "footnote" ||
1363 (t.cs() == "thanks" && context.layout->intitle)) {
1365 context.check_layout(os);
1366 begin_inset(os, "Foot\n");
1367 os << "status collapsed\n\n";
1368 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1372 else if (t.cs() == "marginpar") {
1374 context.check_layout(os);
1375 begin_inset(os, "Marginal\n");
1376 os << "status collapsed\n\n";
1377 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1381 else if (t.cs() == "ensuremath") {
1383 context.check_layout(os);
1384 Context newcontext(false, context.textclass);
1385 newcontext.font = context.font;
1386 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1387 if (s == "±" || s == "³" || s == "²" || s == "µ")
1390 handle_ert(os, "\\ensuremath{" + s + "}",
1394 else if (t.cs() == "hfill") {
1395 context.check_layout(os);
1396 os << "\n\\hfill\n";
1401 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1402 // FIXME: Somehow prevent title layouts if
1403 // "maketitle" was not found
1405 skip_braces(p); // swallow this
1408 else if (t.cs() == "tableofcontents") {
1410 context.check_layout(os);
1411 begin_inset(os, "LatexCommand \\tableofcontents\n");
1413 skip_braces(p); // swallow this
1416 else if (t.cs() == "listoffigures") {
1418 context.check_layout(os);
1419 begin_inset(os, "FloatList figure\n");
1421 skip_braces(p); // swallow this
1424 else if (t.cs() == "listoftables") {
1426 context.check_layout(os);
1427 begin_inset(os, "FloatList table\n");
1429 skip_braces(p); // swallow this
1432 else if (t.cs() == "listof") {
1433 p.skip_spaces(true);
1434 string const name = p.get_token().asString();
1435 if (context.textclass.floats().typeExist(name)) {
1436 context.check_layout(os);
1437 begin_inset(os, "FloatList ");
1440 p.get_token(); // swallow second arg
1442 handle_ert(os, "\\listof{" + name + "}", context);
1445 else if (t.cs() == "textrm")
1446 parse_text_attributes(p, os, FLAG_ITEM, outer,
1447 context, "\\family",
1448 context.font.family, "roman");
1450 else if (t.cs() == "textsf")
1451 parse_text_attributes(p, os, FLAG_ITEM, outer,
1452 context, "\\family",
1453 context.font.family, "sans");
1455 else if (t.cs() == "texttt")
1456 parse_text_attributes(p, os, FLAG_ITEM, outer,
1457 context, "\\family",
1458 context.font.family, "typewriter");
1460 else if (t.cs() == "textmd")
1461 parse_text_attributes(p, os, FLAG_ITEM, outer,
1462 context, "\\series",
1463 context.font.series, "medium");
1465 else if (t.cs() == "textbf")
1466 parse_text_attributes(p, os, FLAG_ITEM, outer,
1467 context, "\\series",
1468 context.font.series, "bold");
1470 else if (t.cs() == "textup")
1471 parse_text_attributes(p, os, FLAG_ITEM, outer,
1473 context.font.shape, "up");
1475 else if (t.cs() == "textit")
1476 parse_text_attributes(p, os, FLAG_ITEM, outer,
1478 context.font.shape, "italic");
1480 else if (t.cs() == "textsl")
1481 parse_text_attributes(p, os, FLAG_ITEM, outer,
1483 context.font.shape, "slanted");
1485 else if (t.cs() == "textsc")
1486 parse_text_attributes(p, os, FLAG_ITEM, outer,
1488 context.font.shape, "smallcaps");
1490 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1491 context.check_layout(os);
1492 Font oldFont = context.font;
1493 context.font.init();
1494 context.font.size = oldFont.size;
1495 os << "\n\\family " << context.font.family << "\n";
1496 os << "\n\\series " << context.font.series << "\n";
1497 os << "\n\\shape " << context.font.shape << "\n";
1498 if (t.cs() == "textnormal") {
1499 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1500 context.font = oldFont;
1501 os << "\n\\shape " << oldFont.shape << "\n";
1502 os << "\n\\series " << oldFont.series << "\n";
1503 os << "\n\\family " << oldFont.family << "\n";
1505 eat_whitespace(p, os, context, false);
1508 else if (t.cs() == "underbar") {
1509 // Do NOT handle \underline.
1510 // \underbar cuts through y, g, q, p etc.,
1511 // \underline does not.
1512 context.check_layout(os);
1513 os << "\n\\bar under\n";
1514 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1515 os << "\n\\bar default\n";
1518 else if (t.cs() == "emph" || t.cs() == "noun") {
1519 context.check_layout(os);
1520 os << "\n\\" << t.cs() << " on\n";
1521 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1522 os << "\n\\" << t.cs() << " default\n";
1525 else if (use_natbib &&
1526 is_known(t.cs(), known_natbib_commands) &&
1527 ((t.cs() != "citefullauthor" &&
1528 t.cs() != "citeyear" &&
1529 t.cs() != "citeyearpar") ||
1530 p.next_token().asInput() != "*")) {
1531 context.check_layout(os);
1533 // \citet[before][after]{a} \citet[after][before]{a}
1534 // \citet[before][]{a} \citet[][before]{a}
1535 // \citet[after]{a} \citet[after]{a}
1536 // \citet{a} \citet{a}
1537 string command = '\\' + t.cs();
1538 if (p.next_token().asInput() == "*") {
1542 if (command == "\\citefullauthor")
1543 // alternative name for "\\citeauthor*"
1544 command = "\\citeauthor*";
1546 // text before the citation
1548 // text after the citation
1551 boost::tie(before, after) = getCiteArguments(p, true);
1552 if (command == "\\cite") {
1553 // \cite without optional argument means
1554 // \citet, \cite with at least one optional
1555 // argument means \citep.
1556 if (before.empty() && after.empty())
1557 command = "\\citet";
1559 command = "\\citep";
1561 if (before.empty() && after == "[]")
1562 // avoid \citet[]{a}
1564 else if (before == "[]" && after == "[]") {
1565 // avoid \citet[][]{a}
1569 begin_inset(os, "LatexCommand ");
1570 os << command << after << before
1571 << '{' << p.verbatim_item() << "}\n";
1575 else if (use_jurabib &&
1576 is_known(t.cs(), known_jurabib_commands)) {
1577 context.check_layout(os);
1578 string const command = '\\' + t.cs();
1579 char argumentOrder = '\0';
1580 vector<string> const & options = used_packages["jurabib"];
1581 if (std::find(options.begin(), options.end(),
1582 "natbiborder") != options.end())
1583 argumentOrder = 'n';
1584 else if (std::find(options.begin(), options.end(),
1585 "jurabiborder") != options.end())
1586 argumentOrder = 'j';
1588 // text before the citation
1590 // text after the citation
1593 boost::tie(before, after) =
1594 getCiteArguments(p, argumentOrder != 'j');
1595 string const citation = p.verbatim_item();
1596 if (!before.empty() && argumentOrder == '\0') {
1597 cerr << "Warning: Assuming argument order "
1598 "of jurabib version 0.6 for\n'"
1599 << command << before << after << '{'
1600 << citation << "}'.\n"
1601 "Add 'jurabiborder' to the jurabib "
1602 "package options if you used an\n"
1603 "earlier jurabib version." << endl;
1605 begin_inset(os, "LatexCommand ");
1606 os << command << after << before
1607 << '{' << citation << "}\n";
1611 else if (is_known(t.cs(), known_latex_commands)) {
1612 // This needs to be after the check for natbib and
1613 // jurabib commands, because "cite" has different
1614 // arguments with natbib and jurabib.
1615 context.check_layout(os);
1616 begin_inset(os, "LatexCommand ");
1617 os << '\\' << t.cs();
1618 // lyx cannot handle newlines in a latex command
1619 // FIXME: Move the substitution into parser::getOpt()?
1620 os << subst(p.getOpt(), "\n", " ");
1621 os << subst(p.getOpt(), "\n", " ");
1622 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1626 else if (is_known(t.cs(), known_quotes)) {
1627 char const * const * where = is_known(t.cs(), known_quotes);
1628 context.check_layout(os);
1629 begin_inset(os, "Quotes ");
1630 os << known_coded_quotes[where - known_quotes];
1632 // LyX adds {} after the quote, so we have to eat
1633 // spaces here if there are any before a possible
1635 eat_whitespace(p, os, context, false);
1639 else if (is_known(t.cs(), known_sizes)) {
1640 char const * const * where = is_known(t.cs(), known_sizes);
1641 context.check_layout(os);
1642 context.font.size = known_coded_sizes[where - known_sizes];
1643 os << "\n\\size " << context.font.size << '\n';
1644 eat_whitespace(p, os, context, false);
1647 else if (is_known(t.cs(), known_font_families)) {
1648 char const * const * where =
1649 is_known(t.cs(), known_font_families);
1650 context.check_layout(os);
1651 context.font.family =
1652 known_coded_font_families[where - known_font_families];
1653 os << "\n\\family " << context.font.family << '\n';
1654 eat_whitespace(p, os, context, false);
1657 else if (is_known(t.cs(), known_font_series)) {
1658 char const * const * where =
1659 is_known(t.cs(), known_font_series);
1660 context.check_layout(os);
1661 context.font.series =
1662 known_coded_font_series[where - known_font_series];
1663 os << "\n\\series " << context.font.series << '\n';
1664 eat_whitespace(p, os, context, false);
1667 else if (is_known(t.cs(), known_font_shapes)) {
1668 char const * const * where =
1669 is_known(t.cs(), known_font_shapes);
1670 context.check_layout(os);
1671 context.font.shape =
1672 known_coded_font_shapes[where - known_font_shapes];
1673 os << "\n\\shape " << context.font.shape << '\n';
1674 eat_whitespace(p, os, context, false);
1676 else if (is_known(t.cs(), known_old_font_families)) {
1677 char const * const * where =
1678 is_known(t.cs(), known_old_font_families);
1679 context.check_layout(os);
1680 string oldsize = context.font.size;
1681 context.font.init();
1682 context.font.size = oldsize;
1683 context.font.family =
1684 known_coded_font_families[where - known_old_font_families];
1685 os << "\n\\family " << context.font.family << "\n"
1686 << "\\series " << context.font.series << "\n"
1687 << "\\shape " << context.font.shape << "\n";
1688 eat_whitespace(p, os, context, false);
1691 else if (is_known(t.cs(), known_old_font_series)) {
1692 char const * const * where =
1693 is_known(t.cs(), known_old_font_series);
1694 context.check_layout(os);
1695 string oldsize = context.font.size;
1696 context.font.init();
1697 context.font.size = oldsize;
1698 context.font.series =
1699 known_coded_font_series[where - known_old_font_series];
1700 os << "\n\\family " << context.font.family << "\n"
1701 << "\\series " << context.font.series << "\n"
1702 << "\\shape " << context.font.shape << "\n";
1703 eat_whitespace(p, os, context, false);
1706 else if (is_known(t.cs(), known_old_font_shapes)) {
1707 char const * const * where =
1708 is_known(t.cs(), known_old_font_shapes);
1709 context.check_layout(os);
1710 string oldsize = context.font.size;
1711 context.font.init();
1712 context.font.size = oldsize;
1713 context.font.shape =
1714 known_coded_font_shapes[where - known_old_font_shapes];
1715 os << "\n\\family " << context.font.family << "\n"
1716 << "\\series " << context.font.series << "\n"
1717 << "\\shape " << context.font.shape << "\n";
1718 eat_whitespace(p, os, context, false);
1721 else if (t.cs() == "LyX" || t.cs() == "TeX"
1722 || t.cs() == "LaTeX") {
1723 context.check_layout(os);
1725 skip_braces(p); // eat {}
1728 else if (t.cs() == "LaTeXe") {
1729 context.check_layout(os);
1731 skip_braces(p); // eat {}
1734 else if (t.cs() == "ldots") {
1735 context.check_layout(os);
1737 os << "\\SpecialChar \\ldots{}\n";
1740 else if (t.cs() == "lyxarrow") {
1741 context.check_layout(os);
1742 os << "\\SpecialChar \\menuseparator\n";
1746 else if (t.cs() == "textcompwordmark") {
1747 context.check_layout(os);
1748 os << "\\SpecialChar \\textcompwordmark{}\n";
1752 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1753 context.check_layout(os);
1754 os << "\\SpecialChar \\@.\n";
1758 else if (t.cs() == "-") {
1759 context.check_layout(os);
1760 os << "\\SpecialChar \\-\n";
1763 else if (t.cs() == "textasciitilde") {
1764 context.check_layout(os);
1769 else if (t.cs() == "textasciicircum") {
1770 context.check_layout(os);
1775 else if (t.cs() == "textbackslash") {
1776 context.check_layout(os);
1777 os << "\n\\backslash\n";
1781 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1782 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1784 context.check_layout(os);
1788 else if (t.cs() == "char") {
1789 context.check_layout(os);
1790 if (p.next_token().character() == '`') {
1792 if (p.next_token().cs() == "\"") {
1797 handle_ert(os, "\\char`", context);
1800 handle_ert(os, "\\char", context);
1804 else if (t.cs() == "\"") {
1805 context.check_layout(os);
1806 string const name = p.verbatim_item();
1807 if (name == "a") os << 'ä';
1808 else if (name == "o") os << 'ö';
1809 else if (name == "u") os << 'ü';
1810 else if (name == "A") os << 'Ä';
1811 else if (name == "O") os << 'Ö';
1812 else if (name == "U") os << 'Ü';
1813 else handle_ert(os, "\"{" + name + "}", context);
1816 // Problem: \= creates a tabstop inside the tabbing environment
1817 // and else an accent. In the latter case we really would want
1818 // \={o} instead of \= o.
1819 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1820 handle_ert(os, t.asInput(), context);
1822 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1823 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1824 // we need the trim as the LyX parser chokes on such spaces
1825 context.check_layout(os);
1826 os << "\n\\i \\" << t.cs() << "{"
1827 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1830 else if (t.cs() == "ss") {
1831 context.check_layout(os);
1835 else if (t.cs() == "i" || t.cs() == "j") {
1836 context.check_layout(os);
1837 os << "\\" << t.cs() << ' ';
1840 else if (t.cs() == "\\") {
1841 context.check_layout(os);
1842 string const next = p.next_token().asInput();
1844 handle_ert(os, "\\\\" + p.getOpt(), context);
1845 else if (next == "*") {
1847 handle_ert(os, "\\\\*" + p.getOpt(), context);
1850 os << "\n\\newline\n";
1854 else if (t.cs() == "input" || t.cs() == "include"
1855 || t.cs() == "verbatiminput") {
1856 string name = '\\' + t.cs();
1857 if (t.cs() == "verbatiminput"
1858 && p.next_token().asInput() == "*")
1859 name += p.get_token().asInput();
1860 context.check_layout(os);
1861 begin_inset(os, "Include ");
1862 string filename(normalize_filename(p.getArg('{', '}')));
1863 string const path = getMasterFilePath();
1864 // We want to preserve relative / absolute filenames,
1865 // therefore path is only used for testing
1866 if (t.cs() == "include" &&
1867 !fs::exists(MakeAbsPath(filename, path))) {
1868 // The file extension is probably missing.
1869 // Now try to find it out.
1870 string const tex_name =
1871 find_file(filename, path,
1872 known_tex_extensions);
1873 if (!tex_name.empty())
1874 filename = tex_name;
1876 if (fs::exists(MakeAbsPath(filename, path))) {
1877 string const abstexname =
1878 MakeAbsPath(filename, path);
1879 string const abslyxname =
1880 ChangeExtension(abstexname, ".lyx");
1881 string const lyxname =
1882 ChangeExtension(filename, ".lyx");
1883 if (t.cs() != "verbatiminput" &&
1884 tex2lyx(abstexname, abslyxname)) {
1885 os << name << '{' << lyxname << "}\n";
1887 os << name << '{' << filename << "}\n";
1890 cerr << "Warning: Could not find included file '"
1891 << filename << "'." << endl;
1892 os << name << '{' << filename << "}\n";
1894 os << "preview false\n";
1898 else if (t.cs() == "fancyhead") {
1899 context.check_layout(os);
1901 ss << "\\fancyhead";
1903 ss << '{' << p.verbatim_item() << "}\n";
1904 handle_ert(os, ss.str(), context);
1907 else if (t.cs() == "bibliographystyle") {
1908 // store new bibliographystyle
1909 bibliographystyle = p.verbatim_item();
1910 // output new bibliographystyle.
1911 // This is only necessary if used in some other macro than \bibliography.
1912 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1915 else if (t.cs() == "bibliography") {
1916 context.check_layout(os);
1917 begin_inset(os, "LatexCommand ");
1919 // Do we have a bibliographystyle set?
1920 if (!bibliographystyle.empty()) {
1921 os << '[' << bibliographystyle << ']';
1923 os << '{' << p.verbatim_item() << "}\n";
1927 else if (t.cs() == "parbox")
1928 parse_box(p, os, FLAG_ITEM, outer, context, true);
1930 else if (t.cs() == "smallskip" ||
1931 t.cs() == "medskip" ||
1932 t.cs() == "bigskip" ||
1933 t.cs() == "vfill") {
1934 context.check_layout(os);
1935 begin_inset(os, "VSpace ");
1941 else if (t.cs() == "newcommand" ||
1942 t.cs() == "providecommand" ||
1943 t.cs() == "renewcommand") {
1944 // these could be handled by parse_command(), but
1945 // we need to call add_known_command() here.
1946 string name = t.asInput();
1947 if (p.next_token().asInput() == "*") {
1948 // Starred form. Eat '*'
1952 string const command = p.verbatim_item();
1953 string const opt1 = p.getOpt();
1954 string const opt2 = p.getFullOpt();
1955 add_known_command(command, opt1, !opt2.empty());
1956 string const ert = name + '{' + command + '}' +
1958 '{' + p.verbatim_item() + '}';
1959 handle_ert(os, ert, context);
1962 else if (t.cs() == "vspace") {
1963 bool starred = false;
1964 if (p.next_token().asInput() == "*") {
1968 string const length = p.verbatim_item();
1971 bool valid = splitLatexLength(length, valstring, unit);
1972 bool known_vspace = false;
1973 bool known_unit = false;
1976 istringstream iss(valstring);
1979 if (unit == "\\smallskipamount") {
1981 known_vspace = true;
1982 } else if (unit == "\\medskipamount") {
1984 known_vspace = true;
1985 } else if (unit == "\\bigskipamount") {
1987 known_vspace = true;
1988 } else if (unit == "\\fill") {
1990 known_vspace = true;
1993 if (!known_vspace) {
1994 switch (unitFromString(unit)) {
2015 if (known_unit || known_vspace) {
2016 // Literal length or known variable
2017 context.check_layout(os);
2018 begin_inset(os, "VSpace ");
2026 // LyX can't handle other length variables in Inset VSpace
2027 string name = t.asInput();
2032 handle_ert(os, name + '{' + unit + '}', context);
2033 else if (value == -1.0)
2034 handle_ert(os, name + "{-" + unit + '}', context);
2036 handle_ert(os, name + '{' + valstring + unit + '}', context);
2038 handle_ert(os, name + '{' + length + '}', context);
2043 //cerr << "#: " << t << " mode: " << mode << endl;
2044 // heuristic: read up to next non-nested space
2046 string s = t.asInput();
2047 string z = p.verbatim_item();
2048 while (p.good() && z != " " && z.size()) {
2049 //cerr << "read: " << z << endl;
2051 z = p.verbatim_item();
2053 cerr << "found ERT: " << s << endl;
2054 handle_ert(os, s + ' ', context);
2056 string name = t.asInput();
2057 if (p.next_token().asInput() == "*") {
2058 // Starred commands like \vspace*{}
2059 p.get_token(); // Eat '*'
2062 if (! parse_command(name, p, os, outer, context))
2063 handle_ert(os, name, context);
2066 if (flags & FLAG_LEAVE) {
2067 flags &= ~FLAG_LEAVE;