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::MakeRelPath;
35 using lyx::support::rtrim;
36 using lyx::support::suffixIs;
37 using lyx::support::contains;
38 using lyx::support::subst;
45 using std::ostringstream;
46 using std::istringstream;
50 namespace fs = boost::filesystem;
53 /// thin wrapper around parse_text using a string
54 string parse_text(Parser & p, unsigned flags, const bool outer,
58 parse_text(p, os, flags, outer, context);
63 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
66 Context newcontext(true, context.textclass);
67 newcontext.font = context.font;
68 parse_text(p, os, flags, outer, newcontext);
69 newcontext.check_end_layout(os);
73 /// parses a paragraph snippet, useful for example for \emph{...}
74 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
77 Context newcontext(false, context.textclass);
78 newcontext.font = context.font;
79 parse_text(p, os, flags, outer, newcontext);
80 // should not be needed
81 newcontext.check_end_layout(os);
87 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
88 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
92 * We can't put these into known_latex_commands because the argument order
93 * is reversed in lyx if there are 2 arguments.
94 * The starred forms are also known.
96 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
97 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
98 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
102 * We can't put these into known_latex_commands because the argument order
103 * is reversed in lyx if there are 2 arguments.
104 * No starred form other than "cite*" known.
106 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
107 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
108 // jurabib commands not (yet) supported by LyX:
109 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
110 // "footciteauthor", "footciteyear", "footciteyearpar",
111 "citefield", "citetitle", "cite*", 0 };
113 /// LaTeX names for quotes
114 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
115 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
117 /// the same as known_quotes with .lyx names
118 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
119 "grd", "gls", "fls", "frd", 0};
121 /// LaTeX names for font sizes
122 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
123 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
125 /// the same as known_sizes with .lyx names
126 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
127 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
129 /// LaTeX 2.09 names for font families
130 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
132 /// LaTeX names for font families
133 char const * const known_font_families[] = { "rmfamily", "sffamily",
136 /// the same as known_old_font_families and known_font_families with .lyx names
137 char const * const known_coded_font_families[] = { "roman", "sans",
140 /// LaTeX 2.09 names for font series
141 char const * const known_old_font_series[] = { "bf", 0};
143 /// LaTeX names for font series
144 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
146 /// the same as known_old_font_series and known_font_series with .lyx names
147 char const * const known_coded_font_series[] = { "bold", "medium", 0};
149 /// LaTeX 2.09 names for font shapes
150 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
152 /// LaTeX names for font shapes
153 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
156 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
157 char const * const known_coded_font_shapes[] = { "italic", "slanted",
158 "smallcaps", "up", 0};
161 * Graphics file extensions known by the dvips driver of the graphics package.
162 * These extensions are used to complete the filename of an included
163 * graphics file if it does not contain an extension.
164 * The order must be the same that latex uses to find a file, because we
165 * will use the first extension that matches.
166 * This is only an approximation for the common cases. If we would want to
167 * do it right in all cases, we would need to know which graphics driver is
168 * used and know the extensions of every driver of the graphics package.
170 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
171 "ps.gz", "eps.Z", "ps.Z", 0};
174 * Graphics file extensions known by the pdftex driver of the graphics package.
175 * \sa known_dvips_graphics_formats
177 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
181 * Known file extensions for TeX files as used by \\include.
183 char const * const known_tex_extensions[] = {"tex", 0};
186 /// splits "x=z, y=b" into a map
187 map<string, string> split_map(string const & s)
189 map<string, string> res;
192 for (size_t i = 0; i < v.size(); ++i) {
193 size_t const pos = v[i].find('=');
194 string const index = v[i].substr(0, pos);
195 string const value = v[i].substr(pos + 1, string::npos);
196 res[trim(index)] = trim(value);
203 * Split a LaTeX length into value and unit.
204 * The latter can be a real unit like "pt", or a latex length variable
205 * like "\textwidth". The unit may contain additional stuff like glue
206 * lengths, but we don't care, because such lengths are ERT anyway.
207 * \returns true if \p value and \p unit are valid.
209 bool splitLatexLength(string const & len, string & value, string & unit)
213 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
214 //'4,5' is a valid LaTeX length number. Change it to '4.5'
215 string const length = subst(len, ',', '.');
216 if (i == string::npos)
219 if (len[0] == '\\') {
220 // We had something like \textwidth without a factor
226 value = trim(string(length, 0, i));
230 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
231 if (contains(len, '\\'))
232 unit = trim(string(len, i));
234 unit = lyx::support::lowercase(trim(string(len, i)));
239 /// A simple function to translate a latex length to something lyx can
240 /// understand. Not perfect, but rather best-effort.
241 bool translate_len(string const & length, string & valstring, string & unit)
243 if (!splitLatexLength(length, valstring, unit))
245 // LyX uses percent values
247 istringstream iss(valstring);
252 string const percentval = oss.str();
254 if (unit.empty() || unit[0] != '\\')
256 string::size_type const i = unit.find(' ');
257 string const endlen = (i == string::npos) ? string() : string(unit, i);
258 if (unit == "\\textwidth") {
259 valstring = percentval;
260 unit = "text%" + endlen;
261 } else if (unit == "\\columnwidth") {
262 valstring = percentval;
263 unit = "col%" + endlen;
264 } else if (unit == "\\paperwidth") {
265 valstring = percentval;
266 unit = "page%" + endlen;
267 } else if (unit == "\\linewidth") {
268 valstring = percentval;
269 unit = "line%" + endlen;
270 } else if (unit == "\\paperheight") {
271 valstring = percentval;
272 unit = "pheight%" + endlen;
273 } else if (unit == "\\textheight") {
274 valstring = percentval;
275 unit = "theight%" + endlen;
281 string translate_len(string const & length)
285 if (translate_len(length, value, unit))
287 // If the input is invalid, return what we have.
293 * Translates a LaTeX length into \p value, \p unit and
294 * \p special parts suitable for a box inset.
295 * The difference from translate_len() is that a box inset knows about
296 * some special "units" that are stored in \p special.
298 void translate_box_len(string const & length, string & value, string & unit, string & special)
300 if (translate_len(length, value, unit)) {
301 if (unit == "\\height" || unit == "\\depth" ||
302 unit == "\\totalheight" || unit == "\\width") {
303 special = unit.substr(1);
304 // The unit is not used, but LyX requires a dummy setting
317 * Find a file with basename \p name in path \p path and an extension
320 string find_file(string const & name, string const & path,
321 char const * const * extensions)
323 for (char const * const * what = extensions; *what; ++what) {
324 // We don't use ChangeExtension() because it does the wrong
325 // thing if name contains a dot.
326 string const trial = name + '.' + (*what);
327 if (fs::exists(MakeAbsPath(trial, path)))
334 void begin_inset(ostream & os, string const & name)
336 os << "\n\\begin_inset " << name;
340 void end_inset(ostream & os)
342 os << "\n\\end_inset\n\n";
346 void skip_braces(Parser & p)
348 if (p.next_token().cat() != catBegin)
351 if (p.next_token().cat() == catEnd) {
359 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
362 // We must have a valid layout before outputting the ERT inset.
363 context.check_layout(os);
365 Context newcontext(true, context.textclass);
366 begin_inset(os, "ERT");
367 os << "\nstatus collapsed\n";
368 newcontext.check_layout(os);
369 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
371 os << "\n\\backslash\n";
372 else if (*it == '\n') {
373 newcontext.new_paragraph(os);
374 newcontext.check_layout(os);
378 newcontext.check_end_layout(os);
383 void handle_comment(ostream & os, string const & s, Context & context)
385 // TODO: Handle this better
386 Context newcontext(true, context.textclass);
387 begin_inset(os, "ERT");
388 os << "\nstatus collapsed\n";
389 newcontext.check_layout(os);
390 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
392 os << "\n\\backslash\n";
396 // make sure that our comment is the last thing on the line
397 newcontext.new_paragraph(os);
398 newcontext.check_layout(os);
399 newcontext.check_end_layout(os);
404 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
406 isLayout(string const name) : name_(name) {}
407 bool operator()(LyXLayout_ptr const & ptr) const {
408 return ptr->latexname() == name_;
415 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
418 LyXTextClass::const_iterator beg = textclass.begin();
419 LyXTextClass::const_iterator end = textclass.end();
421 LyXTextClass::const_iterator
422 it = std::find_if(beg, end, isLayout(name));
424 return (it == end) ? LyXLayout_ptr() : *it;
428 void eat_whitespace(Parser &, ostream &, Context &, bool);
431 void output_command_layout(ostream & os, Parser & p, bool outer,
432 Context & parent_context,
433 LyXLayout_ptr newlayout)
435 parent_context.check_end_layout(os);
436 Context context(true, parent_context.textclass, newlayout,
437 parent_context.layout, parent_context.font);
438 if (parent_context.deeper_paragraph) {
439 // We are beginning a nested environment after a
440 // deeper paragraph inside the outer list environment.
441 // Therefore we don't need to output a "begin deeper".
442 context.need_end_deeper = true;
444 context.check_deeper(os);
445 context.check_layout(os);
446 if (context.layout->optionalargs > 0) {
447 eat_whitespace(p, os, context, false);
448 if (p.next_token().character() == '[') {
449 p.get_token(); // eat '['
450 begin_inset(os, "OptArg\n");
451 os << "status collapsed\n\n";
452 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
454 eat_whitespace(p, os, context, false);
457 parse_text(p, os, FLAG_ITEM, outer, context);
458 context.check_end_layout(os);
459 if (parent_context.deeper_paragraph) {
460 // We must suppress the "end deeper" because we
461 // suppressed the "begin deeper" above.
462 context.need_end_deeper = false;
464 context.check_end_deeper(os);
465 // We don't need really a new paragraph, but
466 // we must make sure that the next item gets a \begin_layout.
467 parent_context.new_paragraph(os);
472 * Output a space if necessary.
473 * This function gets called for every whitespace token.
475 * We have three cases here:
476 * 1. A space must be suppressed. Example: The lyxcode case below
477 * 2. A space may be suppressed. Example: Spaces before "\par"
478 * 3. A space must not be suppressed. Example: A space between two words
480 * We currently handle only 1. and 3 and from 2. only the case of
481 * spaces before newlines as a side effect.
483 * 2. could be used to suppress as many spaces as possible. This has two effects:
484 * - Reimporting LyX generated LaTeX files changes almost no whitespace
485 * - Superflous whitespace from non LyX generated LaTeX files is removed.
486 * The drawback is that the logic inside the function becomes
487 * complicated, and that is the reason why it is not implemented.
489 void check_space(Parser const & p, ostream & os, Context & context)
491 Token const next = p.next_token();
492 Token const curr = p.curr_token();
493 // A space before a single newline and vice versa must be ignored
494 // LyX emits a newline before \end{lyxcode}.
495 // This newline must be ignored,
496 // otherwise LyX will add an additional protected space.
497 if (next.cat() == catSpace ||
498 next.cat() == catNewline ||
499 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
502 context.check_layout(os);
508 * Check whether \p command is a known command. If yes,
509 * handle the command with all arguments.
510 * \return true if the command was parsed, false otherwise.
512 bool parse_command(string const & command, Parser & p, ostream & os,
513 bool outer, Context & context)
515 if (known_commands.find(command) != known_commands.end()) {
516 vector<ArgumentType> const & template_arguments = known_commands[command];
517 string ert = command;
518 size_t no_arguments = template_arguments.size();
519 for (size_t i = 0; i < no_arguments; ++i) {
520 switch (template_arguments[i]) {
522 // This argument contains regular LaTeX
523 handle_ert(os, ert + '{', context);
524 parse_text(p, os, FLAG_ITEM, outer, context);
528 // This argument may contain special characters
529 ert += '{' + p.verbatim_item() + '}';
536 handle_ert(os, ert, context);
543 /// Parses a minipage or parbox
544 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
545 Context & parent_context, bool use_parbox)
549 string height_value = "0";
550 string height_unit = "pt";
551 string height_special = "none";
553 if (p.next_token().asInput() == "[") {
554 position = p.getArg('[', ']');
555 if (position != "t" && position != "c" && position != "b") {
557 cerr << "invalid position for minipage/parbox" << endl;
559 if (p.next_token().asInput() == "[") {
560 latex_height = p.getArg('[', ']');
561 translate_box_len(latex_height, height_value, height_unit, height_special);
563 if (p.next_token().asInput() == "[") {
564 inner_pos = p.getArg('[', ']');
565 if (inner_pos != "c" && inner_pos != "t" &&
566 inner_pos != "b" && inner_pos != "s") {
567 inner_pos = position;
568 cerr << "invalid inner_pos for minipage/parbox"
576 string const latex_width = p.verbatim_item();
577 translate_len(latex_width, width_value, width_unit);
578 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
579 // LyX can't handle length variables
584 ss << "\\begin{minipage}";
585 if (!position.empty())
586 ss << '[' << position << ']';
587 if (!latex_height.empty())
588 ss << '[' << latex_height << ']';
589 if (!inner_pos.empty())
590 ss << '[' << inner_pos << ']';
591 ss << "{" << latex_width << "}";
594 handle_ert(os, ss.str(), parent_context);
595 parent_context.new_paragraph(os);
596 parse_text_in_inset(p, os, flags, outer, parent_context);
598 handle_ert(os, "}", parent_context);
600 handle_ert(os, "\\end{minipage}", parent_context);
602 // LyX does not like empty positions, so we have
603 // to set them to the LaTeX default values here.
604 if (position.empty())
606 if (inner_pos.empty())
607 inner_pos = position;
608 parent_context.check_layout(os);
609 begin_inset(os, "Box Frameless\n");
610 os << "position \"" << position << "\"\n";
611 os << "hor_pos \"c\"\n";
612 os << "has_inner_box 1\n";
613 os << "inner_pos \"" << inner_pos << "\"\n";
614 os << "use_parbox " << use_parbox << "\n";
615 os << "width \"" << width_value << width_unit << "\"\n";
616 os << "special \"none\"\n";
617 os << "height \"" << height_value << height_unit << "\"\n";
618 os << "height_special \"" << height_special << "\"\n";
619 os << "status open\n\n";
620 parse_text_in_inset(p, os, flags, outer, parent_context);
622 #ifdef PRESERVE_LAYOUT
623 // lyx puts a % after the end of the minipage
624 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
626 //handle_comment(os, "%dummy", parent_context);
629 parent_context.new_paragraph(os);
631 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
632 //handle_comment(os, "%dummy", parent_context);
635 // We add a protected space if something real follows
636 if (p.good() && p.next_token().cat() != catComment) {
637 os << "\\InsetSpace ~\n";
645 void parse_environment(Parser & p, ostream & os, bool outer,
646 Context & parent_context)
648 LyXLayout_ptr newlayout;
649 string const name = p.getArg('{', '}');
650 const bool is_starred = suffixIs(name, '*');
651 string const unstarred_name = rtrim(name, "*");
652 eat_whitespace(p, os, parent_context, false);
653 active_environments.push_back(name);
655 if (is_math_env(name)) {
656 parent_context.check_layout(os);
657 begin_inset(os, "Formula ");
658 os << "\\begin{" << name << "}";
659 parse_math(p, os, FLAG_END, MATH_MODE);
660 os << "\\end{" << name << "}";
664 else if (name == "tabular" || name == "longtable") {
665 parent_context.check_layout(os);
666 begin_inset(os, "Tabular ");
667 handle_tabular(p, os, name == "longtable", parent_context);
671 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
672 parent_context.check_layout(os);
673 begin_inset(os, "Float " + unstarred_name + "\n");
674 if (p.next_token().asInput() == "[") {
675 os << "placement " << p.getArg('[', ']') << '\n';
677 os << "wide " << convert<string>(is_starred)
678 << "\nsideways false"
679 << "\nstatus open\n\n";
680 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
682 // We don't need really a new paragraph, but
683 // we must make sure that the next item gets a \begin_layout.
684 parent_context.new_paragraph(os);
687 else if (name == "minipage")
688 parse_box(p, os, FLAG_END, outer, parent_context, false);
690 // Alignment settings
691 else if (name == "center" || name == "flushleft" || name == "flushright" ||
692 name == "centering" || name == "raggedright" || name == "raggedleft") {
693 // We must begin a new paragraph if not already done
694 if (! parent_context.atParagraphStart()) {
695 parent_context.check_end_layout(os);
696 parent_context.new_paragraph(os);
698 if (name == "flushleft" || name == "raggedright")
699 parent_context.add_extra_stuff("\\align left\n");
700 else if (name == "flushright" || name == "raggedleft")
701 parent_context.add_extra_stuff("\\align right\n");
703 parent_context.add_extra_stuff("\\align center\n");
704 parse_text(p, os, FLAG_END, outer, parent_context);
705 // Just in case the environment is empty ..
706 parent_context.extra_stuff.erase();
707 // We must begin a new paragraph to reset the alignment
708 parent_context.new_paragraph(os);
711 // The single '=' is meant here.
712 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
713 newlayout->isEnvironment()) {
714 Context context(true, parent_context.textclass, newlayout,
715 parent_context.layout, parent_context.font);
716 if (parent_context.deeper_paragraph) {
717 // We are beginning a nested environment after a
718 // deeper paragraph inside the outer list environment.
719 // Therefore we don't need to output a "begin deeper".
720 context.need_end_deeper = true;
722 parent_context.check_end_layout(os);
723 switch (context.layout->latextype) {
724 case LATEX_LIST_ENVIRONMENT:
725 context.extra_stuff = "\\labelwidthstring "
726 + p.verbatim_item() + '\n';
729 case LATEX_BIB_ENVIRONMENT:
730 p.verbatim_item(); // swallow next arg
736 context.check_deeper(os);
737 parse_text(p, os, FLAG_END, outer, context);
738 context.check_end_layout(os);
739 if (parent_context.deeper_paragraph) {
740 // We must suppress the "end deeper" because we
741 // suppressed the "begin deeper" above.
742 context.need_end_deeper = false;
744 context.check_end_deeper(os);
745 parent_context.new_paragraph(os);
748 else if (name == "appendix") {
749 // This is no good latex style, but it works and is used in some documents...
750 parent_context.check_end_layout(os);
751 Context context(true, parent_context.textclass, parent_context.layout,
752 parent_context.layout, parent_context.font);
753 context.check_layout(os);
754 os << "\\start_of_appendix\n";
755 parse_text(p, os, FLAG_END, outer, context);
756 context.check_end_layout(os);
759 else if (name == "comment") {
760 parent_context.check_layout(os);
761 begin_inset(os, "Note Comment\n");
762 os << "status open\n";
763 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
767 else if (name == "lyxgreyedout") {
768 parent_context.check_layout(os);
769 begin_inset(os, "Note Greyedout\n");
770 os << "status open\n";
771 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
775 else if (name == "tabbing") {
776 // We need to remember that we have to handle '\=' specially
777 handle_ert(os, "\\begin{" + name + "}", parent_context);
778 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
779 handle_ert(os, "\\end{" + name + "}", parent_context);
783 handle_ert(os, "\\begin{" + name + "}", parent_context);
784 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
785 handle_ert(os, "\\end{" + name + "}", parent_context);
788 active_environments.pop_back();
794 /// parses a comment and outputs it to \p os.
795 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
797 BOOST_ASSERT(t.cat() == catComment);
798 if (!t.cs().empty()) {
799 context.check_layout(os);
800 handle_comment(os, '%' + t.cs(), context);
801 if (p.next_token().cat() == catNewline) {
802 // A newline after a comment line starts a new
804 if(!context.atParagraphStart()) {
805 // Only start a new paragraph if not already
806 // done (we might get called recursively)
807 context.new_paragraph(os);
809 eat_whitespace(p, os, context, true);
819 * Reads spaces and comments until the first non-space, non-comment token.
820 * New paragraphs (double newlines or \\par) are handled like simple spaces
821 * if \p eatParagraph is true.
822 * Spaces are skipped, but comments are written to \p os.
824 void eat_whitespace(Parser & p, ostream & os, Context & context,
828 Token const & t = p.get_token();
829 if (t.cat() == catComment)
830 parse_comment(p, os, t, context);
831 else if ((! eatParagraph && p.isParagraph()) ||
832 (t.cat() != catSpace && t.cat() != catNewline)) {
841 * Set a font attribute, parse text and reset the font attribute.
842 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
843 * \param currentvalue Current value of the attribute. Is set to the new
844 * value during parsing.
845 * \param newvalue New value of the attribute
847 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
848 Context & context, string const & attribute,
849 string & currentvalue, string const & newvalue)
851 context.check_layout(os);
852 string oldvalue = currentvalue;
853 currentvalue = newvalue;
854 os << '\n' << attribute << ' ' << newvalue << "\n";
855 parse_text_snippet(p, os, flags, outer, context);
856 currentvalue = oldvalue;
857 os << '\n' << attribute << ' ' << oldvalue << "\n";
861 /// get the arguments of a natbib or jurabib citation command
862 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
864 // We need to distinguish "" and "[]", so we can't use p.getOpt().
866 // text before the citation
868 // text after the citation
869 string after = p.getFullOpt();
871 if (!after.empty()) {
872 before = p.getFullOpt();
873 if (natbibOrder && !before.empty())
874 std::swap(before, after);
876 return std::make_pair(before, after);
880 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
881 string const normalize_filename(string const & name)
883 Parser p(trim(name, "\""));
886 Token const & t = p.get_token();
887 if (t.cat() != catEscape)
889 else if (t.cs() == "lyxdot") {
890 // This is used by LyX for simple dots in relative
894 } else if (t.cs() == "space") {
904 /// Convert \p name from TeX convention (relative to master file) to LyX
905 /// convention (relative to .lyx file) if it is relative
906 void fix_relative_filename(string & name)
908 if (lyx::support::AbsolutePath(name))
910 name = MakeRelPath(MakeAbsPath(name, getMasterFilePath()),
911 getParentFilePath());
914 } // anonymous namespace
917 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
920 LyXLayout_ptr newlayout;
921 // Store the latest bibliographystyle (needed for bibtex inset)
922 string bibliographystyle;
923 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
924 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
926 Token const & t = p.get_token();
929 cerr << "t: " << t << " flags: " << flags << "\n";
932 if (flags & FLAG_ITEM) {
933 if (t.cat() == catSpace)
937 if (t.cat() == catBegin) {
938 // skip the brace and collect everything to the next matching
940 flags |= FLAG_BRACE_LAST;
944 // handle only this single token, leave the loop if done
948 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
954 if (t.cat() == catMath) {
955 // we are inside some text mode thingy, so opening new math is allowed
956 context.check_layout(os);
957 begin_inset(os, "Formula ");
958 Token const & n = p.get_token();
959 if (n.cat() == catMath && outer) {
960 // TeX's $$...$$ syntax for displayed math
962 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
964 p.get_token(); // skip the second '$' token
966 // simple $...$ stuff
969 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
975 else if (t.cat() == catSuper || t.cat() == catSub)
976 cerr << "catcode " << t << " illegal in text mode\n";
978 // Basic support for english quotes. This should be
979 // extended to other quotes, but is not so easy (a
980 // left english quote is the same as a right german
982 else if (t.asInput() == "`"
983 && p.next_token().asInput() == "`") {
984 context.check_layout(os);
985 begin_inset(os, "Quotes ");
991 else if (t.asInput() == "'"
992 && p.next_token().asInput() == "'") {
993 context.check_layout(os);
994 begin_inset(os, "Quotes ");
1001 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1002 check_space(p, os, context);
1004 else if (t.cat() == catLetter ||
1005 t.cat() == catOther ||
1006 t.cat() == catAlign ||
1007 t.cat() == catParameter) {
1008 // This translates "&" to "\\&" which may be wrong...
1009 context.check_layout(os);
1010 os << t.character();
1013 else if (p.isParagraph()) {
1014 context.new_paragraph(os);
1015 eat_whitespace(p, os, context, true);
1018 else if (t.cat() == catActive) {
1019 context.check_layout(os);
1020 if (t.character() == '~') {
1021 if (context.layout->free_spacing)
1024 os << "\\InsetSpace ~\n";
1026 os << t.character();
1029 else if (t.cat() == catBegin) {
1030 context.check_layout(os);
1031 // special handling of font attribute changes
1032 Token const prev = p.prev_token();
1033 Token const next = p.next_token();
1034 Font const oldFont = context.font;
1035 string const s = parse_text(p, FLAG_BRACE_LAST, outer,
1037 context.font = oldFont;
1038 if (s.empty() && (p.next_token().character() == '`' ||
1039 (prev.character() == '-' &&
1040 p.next_token().character() == '-')))
1041 ; // ignore it in {}`` or -{}-
1042 else if (s == "[" || s == "]" || s == "*")
1044 else if (is_known(next.cs(), known_sizes)) {
1045 // s will change the size, so we must reset
1048 if (!context.atParagraphStart())
1050 << context.font.size << "\n";
1051 } else if (is_known(next.cs(), known_font_families)) {
1052 // s will change the font family, so we must
1055 if (!context.atParagraphStart())
1057 << context.font.family << "\n";
1058 } else if (is_known(next.cs(), known_font_series)) {
1059 // s will change the font series, so we must
1062 if (!context.atParagraphStart())
1064 << context.font.series << "\n";
1065 } else if (is_known(next.cs(), known_font_shapes)) {
1066 // s will change the font shape, so we must
1069 if (!context.atParagraphStart())
1071 << context.font.shape << "\n";
1072 } else if (is_known(next.cs(), known_old_font_families) ||
1073 is_known(next.cs(), known_old_font_series) ||
1074 is_known(next.cs(), known_old_font_shapes)) {
1075 // s will change the font family, series
1076 // and shape, so we must reset it here
1078 if (!context.atParagraphStart())
1080 << context.font.family
1082 << context.font.series
1084 << context.font.shape << "\n";
1086 handle_ert(os, "{", context, false);
1087 // s will end the current layout and begin a
1088 // new one if necessary
1090 handle_ert(os, "}", context);
1094 else if (t.cat() == catEnd) {
1095 if (flags & FLAG_BRACE_LAST) {
1098 cerr << "stray '}' in text\n";
1099 handle_ert(os, "}", context);
1102 else if (t.cat() == catComment)
1103 parse_comment(p, os, t, context);
1106 // control sequences
1109 else if (t.cs() == "(") {
1110 context.check_layout(os);
1111 begin_inset(os, "Formula");
1113 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1118 else if (t.cs() == "[") {
1119 context.check_layout(os);
1120 begin_inset(os, "Formula");
1122 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1127 else if (t.cs() == "begin")
1128 parse_environment(p, os, outer, context);
1130 else if (t.cs() == "end") {
1131 if (flags & FLAG_END) {
1132 // eat environment name
1133 string const name = p.getArg('{', '}');
1134 if (name != active_environment())
1135 cerr << "\\end{" + name + "} does not match \\begin{"
1136 + active_environment() + "}\n";
1139 p.error("found 'end' unexpectedly");
1142 else if (t.cs() == "item") {
1145 bool optarg = false;
1146 if (p.next_token().character() == '[') {
1147 p.get_token(); // eat '['
1148 Context newcontext(false, context.textclass);
1149 newcontext.font = context.font;
1150 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1154 context.check_layout(os);
1156 if (context.layout->labeltype != LABEL_MANUAL) {
1157 // lyx does not support \item[\mybullet]
1158 // in itemize environments
1159 handle_ert(os, "[", context);
1161 handle_ert(os, "]", context);
1162 } else if (!s.empty()) {
1163 // The space is needed to separate the
1164 // item from the rest of the sentence.
1166 eat_whitespace(p, os, context, false);
1171 else if (t.cs() == "bibitem") {
1173 context.check_layout(os);
1176 os << '{' << p.verbatim_item() << '}' << "\n";
1179 else if (t.cs() == "def") {
1180 context.check_layout(os);
1181 eat_whitespace(p, os, context, false);
1182 string name = p.get_token().cs();
1183 while (p.next_token().cat() != catBegin)
1184 name += p.get_token().asString();
1185 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1188 else if (t.cs() == "noindent") {
1190 context.add_extra_stuff("\\noindent\n");
1193 else if (t.cs() == "appendix") {
1194 context.add_extra_stuff("\\start_of_appendix\n");
1195 // We need to start a new paragraph. Otherwise the
1196 // appendix in 'bla\appendix\chapter{' would start
1198 context.new_paragraph(os);
1199 // We need to make sure that the paragraph is
1200 // generated even if it is empty. Otherwise the
1201 // appendix in '\par\appendix\par\chapter{' would
1203 context.check_layout(os);
1204 // FIXME: This is a hack to prevent paragraph
1205 // deletion if it is empty. Handle this better!
1207 "%dummy comment inserted by tex2lyx to "
1208 "ensure that this paragraph is not empty",
1210 // Both measures above may generate an additional
1211 // empty paragraph, but that does not hurt, because
1212 // whitespace does not matter here.
1213 eat_whitespace(p, os, context, true);
1216 // Must attempt to parse "Section*" before "Section".
1217 else if ((p.next_token().asInput() == "*") &&
1218 // The single '=' is meant here.
1219 (newlayout = findLayout(context.textclass,
1220 t.cs() + '*')).get() &&
1221 newlayout->isCommand()) {
1223 output_command_layout(os, p, outer, context, newlayout);
1227 // The single '=' is meant here.
1228 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1229 newlayout->isCommand()) {
1230 output_command_layout(os, p, outer, context, newlayout);
1234 else if (t.cs() == "includegraphics") {
1235 bool const clip = p.next_token().asInput() == "*";
1238 map<string, string> opts = split_map(p.getArg('[', ']'));
1240 opts["clip"] = string();
1241 string name = normalize_filename(p.verbatim_item());
1243 string const path = getMasterFilePath();
1244 // We want to preserve relative / absolute filenames,
1245 // therefore path is only used for testing
1246 if (!fs::exists(MakeAbsPath(name, path))) {
1247 // The file extension is probably missing.
1248 // Now try to find it out.
1249 string const dvips_name =
1250 find_file(name, path,
1251 known_dvips_graphics_formats);
1252 string const pdftex_name =
1253 find_file(name, path,
1254 known_pdftex_graphics_formats);
1255 if (!dvips_name.empty()) {
1256 if (!pdftex_name.empty()) {
1257 cerr << "This file contains the "
1259 "\"\\includegraphics{"
1261 "However, files\n\""
1262 << dvips_name << "\" and\n\""
1263 << pdftex_name << "\"\n"
1264 "both exist, so I had to make a "
1265 "choice and took the first one.\n"
1266 "Please move the unwanted one "
1267 "someplace else and try again\n"
1268 "if my choice was wrong."
1272 } else if (!pdftex_name.empty())
1276 if (fs::exists(MakeAbsPath(name, path)))
1277 fix_relative_filename(name);
1279 cerr << "Warning: Could not find graphics file '"
1280 << name << "'." << endl;
1282 context.check_layout(os);
1283 begin_inset(os, "Graphics ");
1284 os << "\n\tfilename " << name << '\n';
1285 if (opts.find("width") != opts.end())
1287 << translate_len(opts["width"]) << '\n';
1288 if (opts.find("height") != opts.end())
1290 << translate_len(opts["height"]) << '\n';
1291 if (opts.find("scale") != opts.end()) {
1292 istringstream iss(opts["scale"]);
1296 os << "\tscale " << val << '\n';
1298 if (opts.find("angle") != opts.end())
1299 os << "\trotateAngle "
1300 << opts["angle"] << '\n';
1301 if (opts.find("origin") != opts.end()) {
1303 string const opt = opts["origin"];
1304 if (opt.find('l') != string::npos) ss << "left";
1305 if (opt.find('r') != string::npos) ss << "right";
1306 if (opt.find('c') != string::npos) ss << "center";
1307 if (opt.find('t') != string::npos) ss << "Top";
1308 if (opt.find('b') != string::npos) ss << "Bottom";
1309 if (opt.find('B') != string::npos) ss << "Baseline";
1310 if (!ss.str().empty())
1311 os << "\trotateOrigin " << ss.str() << '\n';
1313 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1315 if (opts.find("keepaspectratio") != opts.end())
1316 os << "\tkeepAspectRatio\n";
1317 if (opts.find("clip") != opts.end())
1319 if (opts.find("draft") != opts.end())
1321 if (opts.find("bb") != opts.end())
1322 os << "\tBoundingBox "
1323 << opts["bb"] << '\n';
1324 int numberOfbbOptions = 0;
1325 if (opts.find("bbllx") != opts.end())
1326 numberOfbbOptions++;
1327 if (opts.find("bblly") != opts.end())
1328 numberOfbbOptions++;
1329 if (opts.find("bburx") != opts.end())
1330 numberOfbbOptions++;
1331 if (opts.find("bbury") != opts.end())
1332 numberOfbbOptions++;
1333 if (numberOfbbOptions == 4)
1334 os << "\tBoundingBox "
1335 << opts["bbllx"] << opts["bblly"]
1336 << opts["bburx"] << opts["bbury"] << '\n';
1337 else if (numberOfbbOptions > 0)
1338 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1339 numberOfbbOptions = 0;
1340 if (opts.find("natwidth") != opts.end())
1341 numberOfbbOptions++;
1342 if (opts.find("natheight") != opts.end())
1343 numberOfbbOptions++;
1344 if (numberOfbbOptions == 2)
1345 os << "\tBoundingBox 0bp 0bp "
1346 << opts["natwidth"] << opts["natheight"] << '\n';
1347 else if (numberOfbbOptions > 0)
1348 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1349 ostringstream special;
1350 if (opts.find("hiresbb") != opts.end())
1351 special << "hiresbb,";
1352 if (opts.find("trim") != opts.end())
1354 if (opts.find("viewport") != opts.end())
1355 special << "viewport=" << opts["viewport"] << ',';
1356 if (opts.find("totalheight") != opts.end())
1357 special << "totalheight=" << opts["totalheight"] << ',';
1358 if (opts.find("type") != opts.end())
1359 special << "type=" << opts["type"] << ',';
1360 if (opts.find("ext") != opts.end())
1361 special << "ext=" << opts["ext"] << ',';
1362 if (opts.find("read") != opts.end())
1363 special << "read=" << opts["read"] << ',';
1364 if (opts.find("command") != opts.end())
1365 special << "command=" << opts["command"] << ',';
1366 string s_special = special.str();
1367 if (!s_special.empty()) {
1368 // We had special arguments. Remove the trailing ','.
1369 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1371 // TODO: Handle the unknown settings better.
1372 // Warn about invalid options.
1373 // Check whether some option was given twice.
1377 else if (t.cs() == "footnote" ||
1378 (t.cs() == "thanks" && context.layout->intitle)) {
1380 context.check_layout(os);
1381 begin_inset(os, "Foot\n");
1382 os << "status collapsed\n\n";
1383 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1387 else if (t.cs() == "marginpar") {
1389 context.check_layout(os);
1390 begin_inset(os, "Marginal\n");
1391 os << "status collapsed\n\n";
1392 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1396 else if (t.cs() == "ensuremath") {
1398 context.check_layout(os);
1399 Context newcontext(false, context.textclass);
1400 newcontext.font = context.font;
1401 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1402 if (s == "±" || s == "³" || s == "²" || s == "µ")
1405 handle_ert(os, "\\ensuremath{" + s + "}",
1409 else if (t.cs() == "hfill") {
1410 context.check_layout(os);
1411 os << "\n\\hfill\n";
1416 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1417 // FIXME: Somehow prevent title layouts if
1418 // "maketitle" was not found
1420 skip_braces(p); // swallow this
1423 else if (t.cs() == "tableofcontents") {
1425 context.check_layout(os);
1426 begin_inset(os, "LatexCommand \\tableofcontents\n");
1428 skip_braces(p); // swallow this
1431 else if (t.cs() == "listoffigures") {
1433 context.check_layout(os);
1434 begin_inset(os, "FloatList figure\n");
1436 skip_braces(p); // swallow this
1439 else if (t.cs() == "listoftables") {
1441 context.check_layout(os);
1442 begin_inset(os, "FloatList table\n");
1444 skip_braces(p); // swallow this
1447 else if (t.cs() == "listof") {
1448 p.skip_spaces(true);
1449 string const name = p.get_token().asString();
1450 if (context.textclass.floats().typeExist(name)) {
1451 context.check_layout(os);
1452 begin_inset(os, "FloatList ");
1455 p.get_token(); // swallow second arg
1457 handle_ert(os, "\\listof{" + name + "}", context);
1460 else if (t.cs() == "textrm")
1461 parse_text_attributes(p, os, FLAG_ITEM, outer,
1462 context, "\\family",
1463 context.font.family, "roman");
1465 else if (t.cs() == "textsf")
1466 parse_text_attributes(p, os, FLAG_ITEM, outer,
1467 context, "\\family",
1468 context.font.family, "sans");
1470 else if (t.cs() == "texttt")
1471 parse_text_attributes(p, os, FLAG_ITEM, outer,
1472 context, "\\family",
1473 context.font.family, "typewriter");
1475 else if (t.cs() == "textmd")
1476 parse_text_attributes(p, os, FLAG_ITEM, outer,
1477 context, "\\series",
1478 context.font.series, "medium");
1480 else if (t.cs() == "textbf")
1481 parse_text_attributes(p, os, FLAG_ITEM, outer,
1482 context, "\\series",
1483 context.font.series, "bold");
1485 else if (t.cs() == "textup")
1486 parse_text_attributes(p, os, FLAG_ITEM, outer,
1488 context.font.shape, "up");
1490 else if (t.cs() == "textit")
1491 parse_text_attributes(p, os, FLAG_ITEM, outer,
1493 context.font.shape, "italic");
1495 else if (t.cs() == "textsl")
1496 parse_text_attributes(p, os, FLAG_ITEM, outer,
1498 context.font.shape, "slanted");
1500 else if (t.cs() == "textsc")
1501 parse_text_attributes(p, os, FLAG_ITEM, outer,
1503 context.font.shape, "smallcaps");
1505 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1506 context.check_layout(os);
1507 Font oldFont = context.font;
1508 context.font.init();
1509 context.font.size = oldFont.size;
1510 os << "\n\\family " << context.font.family << "\n";
1511 os << "\n\\series " << context.font.series << "\n";
1512 os << "\n\\shape " << context.font.shape << "\n";
1513 if (t.cs() == "textnormal") {
1514 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1515 context.font = oldFont;
1516 os << "\n\\shape " << oldFont.shape << "\n";
1517 os << "\n\\series " << oldFont.series << "\n";
1518 os << "\n\\family " << oldFont.family << "\n";
1520 eat_whitespace(p, os, context, false);
1523 else if (t.cs() == "underbar") {
1524 // Do NOT handle \underline.
1525 // \underbar cuts through y, g, q, p etc.,
1526 // \underline does not.
1527 context.check_layout(os);
1528 os << "\n\\bar under\n";
1529 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1530 os << "\n\\bar default\n";
1533 else if (t.cs() == "emph" || t.cs() == "noun") {
1534 context.check_layout(os);
1535 os << "\n\\" << t.cs() << " on\n";
1536 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1537 os << "\n\\" << t.cs() << " default\n";
1540 else if (use_natbib &&
1541 is_known(t.cs(), known_natbib_commands) &&
1542 ((t.cs() != "citefullauthor" &&
1543 t.cs() != "citeyear" &&
1544 t.cs() != "citeyearpar") ||
1545 p.next_token().asInput() != "*")) {
1546 context.check_layout(os);
1548 // \citet[before][after]{a} \citet[after][before]{a}
1549 // \citet[before][]{a} \citet[][before]{a}
1550 // \citet[after]{a} \citet[after]{a}
1551 // \citet{a} \citet{a}
1552 string command = '\\' + t.cs();
1553 if (p.next_token().asInput() == "*") {
1557 if (command == "\\citefullauthor")
1558 // alternative name for "\\citeauthor*"
1559 command = "\\citeauthor*";
1561 // text before the citation
1563 // text after the citation
1566 boost::tie(before, after) = getCiteArguments(p, true);
1567 if (command == "\\cite") {
1568 // \cite without optional argument means
1569 // \citet, \cite with at least one optional
1570 // argument means \citep.
1571 if (before.empty() && after.empty())
1572 command = "\\citet";
1574 command = "\\citep";
1576 if (before.empty() && after == "[]")
1577 // avoid \citet[]{a}
1579 else if (before == "[]" && after == "[]") {
1580 // avoid \citet[][]{a}
1584 begin_inset(os, "LatexCommand ");
1585 os << command << after << before
1586 << '{' << p.verbatim_item() << "}\n";
1590 else if (use_jurabib &&
1591 is_known(t.cs(), known_jurabib_commands)) {
1592 context.check_layout(os);
1593 string const command = '\\' + t.cs();
1594 char argumentOrder = '\0';
1595 vector<string> const & options = used_packages["jurabib"];
1596 if (std::find(options.begin(), options.end(),
1597 "natbiborder") != options.end())
1598 argumentOrder = 'n';
1599 else if (std::find(options.begin(), options.end(),
1600 "jurabiborder") != options.end())
1601 argumentOrder = 'j';
1603 // text before the citation
1605 // text after the citation
1608 boost::tie(before, after) =
1609 getCiteArguments(p, argumentOrder != 'j');
1610 string const citation = p.verbatim_item();
1611 if (!before.empty() && argumentOrder == '\0') {
1612 cerr << "Warning: Assuming argument order "
1613 "of jurabib version 0.6 for\n'"
1614 << command << before << after << '{'
1615 << citation << "}'.\n"
1616 "Add 'jurabiborder' to the jurabib "
1617 "package options if you used an\n"
1618 "earlier jurabib version." << endl;
1620 begin_inset(os, "LatexCommand ");
1621 os << command << after << before
1622 << '{' << citation << "}\n";
1626 else if (is_known(t.cs(), known_latex_commands)) {
1627 // This needs to be after the check for natbib and
1628 // jurabib commands, because "cite" has different
1629 // arguments with natbib and jurabib.
1630 context.check_layout(os);
1631 begin_inset(os, "LatexCommand ");
1632 os << '\\' << t.cs();
1633 // lyx cannot handle newlines in a latex command
1634 // FIXME: Move the substitution into parser::getOpt()?
1635 os << subst(p.getOpt(), "\n", " ");
1636 os << subst(p.getOpt(), "\n", " ");
1637 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1641 else if (is_known(t.cs(), known_quotes)) {
1642 char const * const * where = is_known(t.cs(), known_quotes);
1643 context.check_layout(os);
1644 begin_inset(os, "Quotes ");
1645 os << known_coded_quotes[where - known_quotes];
1647 // LyX adds {} after the quote, so we have to eat
1648 // spaces here if there are any before a possible
1650 eat_whitespace(p, os, context, false);
1654 else if (is_known(t.cs(), known_sizes)) {
1655 char const * const * where = is_known(t.cs(), known_sizes);
1656 context.check_layout(os);
1657 context.font.size = known_coded_sizes[where - known_sizes];
1658 os << "\n\\size " << context.font.size << '\n';
1659 eat_whitespace(p, os, context, false);
1662 else if (is_known(t.cs(), known_font_families)) {
1663 char const * const * where =
1664 is_known(t.cs(), known_font_families);
1665 context.check_layout(os);
1666 context.font.family =
1667 known_coded_font_families[where - known_font_families];
1668 // FIXME: Only do this if it is necessary
1669 os << "\n\\family " << context.font.family << '\n';
1670 eat_whitespace(p, os, context, false);
1673 else if (is_known(t.cs(), known_font_series)) {
1674 char const * const * where =
1675 is_known(t.cs(), known_font_series);
1676 context.check_layout(os);
1677 context.font.series =
1678 known_coded_font_series[where - known_font_series];
1679 // FIXME: Only do this if it is necessary
1680 os << "\n\\series " << context.font.series << '\n';
1681 eat_whitespace(p, os, context, false);
1684 else if (is_known(t.cs(), known_font_shapes)) {
1685 char const * const * where =
1686 is_known(t.cs(), known_font_shapes);
1687 context.check_layout(os);
1688 context.font.shape =
1689 known_coded_font_shapes[where - known_font_shapes];
1690 // FIXME: Only do this if it is necessary
1691 os << "\n\\shape " << context.font.shape << '\n';
1692 eat_whitespace(p, os, context, false);
1694 else if (is_known(t.cs(), known_old_font_families)) {
1695 char const * const * where =
1696 is_known(t.cs(), known_old_font_families);
1697 context.check_layout(os);
1698 string oldsize = context.font.size;
1699 context.font.init();
1700 context.font.size = oldsize;
1701 context.font.family =
1702 known_coded_font_families[where - known_old_font_families];
1703 // FIXME: Only do this if it is necessary
1704 os << "\n\\family " << context.font.family << "\n"
1705 << "\\series " << context.font.series << "\n"
1706 << "\\shape " << context.font.shape << "\n";
1707 eat_whitespace(p, os, context, false);
1710 else if (is_known(t.cs(), known_old_font_series)) {
1711 char const * const * where =
1712 is_known(t.cs(), known_old_font_series);
1713 context.check_layout(os);
1714 string oldsize = context.font.size;
1715 context.font.init();
1716 context.font.size = oldsize;
1717 context.font.series =
1718 known_coded_font_series[where - known_old_font_series];
1719 // FIXME: Only do this if it is necessary
1720 os << "\n\\family " << context.font.family << "\n"
1721 << "\\series " << context.font.series << "\n"
1722 << "\\shape " << context.font.shape << "\n";
1723 eat_whitespace(p, os, context, false);
1726 else if (is_known(t.cs(), known_old_font_shapes)) {
1727 char const * const * where =
1728 is_known(t.cs(), known_old_font_shapes);
1729 context.check_layout(os);
1730 string oldsize = context.font.size;
1731 context.font.init();
1732 context.font.size = oldsize;
1733 context.font.shape =
1734 known_coded_font_shapes[where - known_old_font_shapes];
1735 // FIXME: Only do this if it is necessary
1736 os << "\n\\family " << context.font.family << "\n"
1737 << "\\series " << context.font.series << "\n"
1738 << "\\shape " << context.font.shape << "\n";
1739 eat_whitespace(p, os, context, false);
1742 else if (t.cs() == "LyX" || t.cs() == "TeX"
1743 || t.cs() == "LaTeX") {
1744 context.check_layout(os);
1746 skip_braces(p); // eat {}
1749 else if (t.cs() == "LaTeXe") {
1750 context.check_layout(os);
1752 skip_braces(p); // eat {}
1755 else if (t.cs() == "ldots") {
1756 context.check_layout(os);
1758 os << "\\SpecialChar \\ldots{}\n";
1761 else if (t.cs() == "lyxarrow") {
1762 context.check_layout(os);
1763 os << "\\SpecialChar \\menuseparator\n";
1767 else if (t.cs() == "textcompwordmark") {
1768 context.check_layout(os);
1769 os << "\\SpecialChar \\textcompwordmark{}\n";
1773 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1774 context.check_layout(os);
1775 os << "\\SpecialChar \\@.\n";
1779 else if (t.cs() == "-") {
1780 context.check_layout(os);
1781 os << "\\SpecialChar \\-\n";
1784 else if (t.cs() == "textasciitilde") {
1785 context.check_layout(os);
1790 else if (t.cs() == "textasciicircum") {
1791 context.check_layout(os);
1796 else if (t.cs() == "textbackslash") {
1797 context.check_layout(os);
1798 os << "\n\\backslash\n";
1802 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1803 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1805 context.check_layout(os);
1809 else if (t.cs() == "char") {
1810 context.check_layout(os);
1811 if (p.next_token().character() == '`') {
1813 if (p.next_token().cs() == "\"") {
1818 handle_ert(os, "\\char`", context);
1821 handle_ert(os, "\\char", context);
1825 else if (t.cs() == "\"") {
1826 context.check_layout(os);
1827 string const name = p.verbatim_item();
1828 if (name == "a") os << 'ä';
1829 else if (name == "o") os << 'ö';
1830 else if (name == "u") os << 'ü';
1831 else if (name == "A") os << 'Ä';
1832 else if (name == "O") os << 'Ö';
1833 else if (name == "U") os << 'Ü';
1834 else handle_ert(os, "\"{" + name + "}", context);
1837 // Problem: \= creates a tabstop inside the tabbing environment
1838 // and else an accent. In the latter case we really would want
1839 // \={o} instead of \= o.
1840 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1841 handle_ert(os, t.asInput(), context);
1843 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1844 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1845 // we need the trim as the LyX parser chokes on such spaces
1846 context.check_layout(os);
1847 os << "\n\\i \\" << t.cs() << "{"
1848 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1851 else if (t.cs() == "ss") {
1852 context.check_layout(os);
1854 skip_braces(p); // eat {}
1857 else if (t.cs() == "i" || t.cs() == "j") {
1858 context.check_layout(os);
1859 os << "\\" << t.cs() << ' ';
1860 skip_braces(p); // eat {}
1863 else if (t.cs() == "\\") {
1864 context.check_layout(os);
1865 string const next = p.next_token().asInput();
1867 handle_ert(os, "\\\\" + p.getOpt(), context);
1868 else if (next == "*") {
1870 handle_ert(os, "\\\\*" + p.getOpt(), context);
1873 os << "\n\\newline\n";
1877 else if (t.cs() == "input" || t.cs() == "include"
1878 || t.cs() == "verbatiminput") {
1879 string name = '\\' + t.cs();
1880 if (t.cs() == "verbatiminput"
1881 && p.next_token().asInput() == "*")
1882 name += p.get_token().asInput();
1883 context.check_layout(os);
1884 begin_inset(os, "Include ");
1885 string filename(normalize_filename(p.getArg('{', '}')));
1886 string const path = getMasterFilePath();
1887 // We want to preserve relative / absolute filenames,
1888 // therefore path is only used for testing
1889 if (t.cs() == "include" &&
1890 !fs::exists(MakeAbsPath(filename, path))) {
1891 // The file extension is probably missing.
1892 // Now try to find it out.
1893 string const tex_name =
1894 find_file(filename, path,
1895 known_tex_extensions);
1896 if (!tex_name.empty())
1897 filename = tex_name;
1899 if (fs::exists(MakeAbsPath(filename, path))) {
1900 string const abstexname =
1901 MakeAbsPath(filename, path);
1902 string const abslyxname =
1903 ChangeExtension(abstexname, ".lyx");
1904 fix_relative_filename(filename);
1905 string const lyxname =
1906 ChangeExtension(filename, ".lyx");
1907 if (t.cs() != "verbatiminput" &&
1908 tex2lyx(abstexname, abslyxname)) {
1909 os << name << '{' << lyxname << "}\n";
1911 os << name << '{' << filename << "}\n";
1914 cerr << "Warning: Could not find included file '"
1915 << filename << "'." << endl;
1916 os << name << '{' << filename << "}\n";
1918 os << "preview false\n";
1922 else if (t.cs() == "fancyhead") {
1923 context.check_layout(os);
1925 ss << "\\fancyhead";
1927 ss << '{' << p.verbatim_item() << "}\n";
1928 handle_ert(os, ss.str(), context);
1931 else if (t.cs() == "bibliographystyle") {
1932 // store new bibliographystyle
1933 bibliographystyle = p.verbatim_item();
1934 // output new bibliographystyle.
1935 // This is only necessary if used in some other macro than \bibliography.
1936 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1939 else if (t.cs() == "bibliography") {
1940 context.check_layout(os);
1941 begin_inset(os, "LatexCommand ");
1943 // Do we have a bibliographystyle set?
1944 if (!bibliographystyle.empty()) {
1945 os << '[' << bibliographystyle << ']';
1947 os << '{' << p.verbatim_item() << "}\n";
1951 else if (t.cs() == "parbox")
1952 parse_box(p, os, FLAG_ITEM, outer, context, true);
1954 else if (t.cs() == "smallskip" ||
1955 t.cs() == "medskip" ||
1956 t.cs() == "bigskip" ||
1957 t.cs() == "vfill") {
1958 context.check_layout(os);
1959 begin_inset(os, "VSpace ");
1965 else if (t.cs() == "newcommand" ||
1966 t.cs() == "providecommand" ||
1967 t.cs() == "renewcommand") {
1968 // these could be handled by parse_command(), but
1969 // we need to call add_known_command() here.
1970 string name = t.asInput();
1971 if (p.next_token().asInput() == "*") {
1972 // Starred form. Eat '*'
1976 string const command = p.verbatim_item();
1977 string const opt1 = p.getOpt();
1978 string const opt2 = p.getFullOpt();
1979 add_known_command(command, opt1, !opt2.empty());
1980 string const ert = name + '{' + command + '}' +
1982 '{' + p.verbatim_item() + '}';
1983 handle_ert(os, ert, context);
1986 else if (t.cs() == "vspace") {
1987 bool starred = false;
1988 if (p.next_token().asInput() == "*") {
1992 string const length = p.verbatim_item();
1995 bool valid = splitLatexLength(length, valstring, unit);
1996 bool known_vspace = false;
1997 bool known_unit = false;
2000 istringstream iss(valstring);
2003 if (unit == "\\smallskipamount") {
2005 known_vspace = true;
2006 } else if (unit == "\\medskipamount") {
2008 known_vspace = true;
2009 } else if (unit == "\\bigskipamount") {
2011 known_vspace = true;
2012 } else if (unit == "\\fill") {
2014 known_vspace = true;
2017 if (!known_vspace) {
2018 switch (unitFromString(unit)) {
2039 if (known_unit || known_vspace) {
2040 // Literal length or known variable
2041 context.check_layout(os);
2042 begin_inset(os, "VSpace ");
2050 // LyX can't handle other length variables in Inset VSpace
2051 string name = t.asInput();
2056 handle_ert(os, name + '{' + unit + '}', context);
2057 else if (value == -1.0)
2058 handle_ert(os, name + "{-" + unit + '}', context);
2060 handle_ert(os, name + '{' + valstring + unit + '}', context);
2062 handle_ert(os, name + '{' + length + '}', context);
2067 //cerr << "#: " << t << " mode: " << mode << endl;
2068 // heuristic: read up to next non-nested space
2070 string s = t.asInput();
2071 string z = p.verbatim_item();
2072 while (p.good() && z != " " && z.size()) {
2073 //cerr << "read: " << z << endl;
2075 z = p.verbatim_item();
2077 cerr << "found ERT: " << s << endl;
2078 handle_ert(os, s + ' ', context);
2080 string name = t.asInput();
2081 if (p.next_token().asInput() == "*") {
2082 // Starred commands like \vspace*{}
2083 p.get_token(); // Eat '*'
2086 if (! parse_command(name, p, os, outer, context))
2087 handle_ert(os, name, context);
2090 if (flags & FLAG_LEAVE) {
2091 flags &= ~FLAG_LEAVE;