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) {
360 void handle_ert(ostream & os, string const & s, Context & context,
361 bool check_layout = true)
364 // We must have a valid layout before outputting the ERT inset.
365 context.check_layout(os);
367 Context newcontext(true, context.textclass);
368 begin_inset(os, "ERT");
369 os << "\nstatus collapsed\n";
370 newcontext.check_layout(os);
371 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
373 os << "\n\\backslash\n";
374 else if (*it == '\n') {
375 newcontext.new_paragraph(os);
376 newcontext.check_layout(os);
380 newcontext.check_end_layout(os);
385 void handle_comment(ostream & os, string const & s, Context & context)
387 // TODO: Handle this better
388 Context newcontext(true, context.textclass);
389 begin_inset(os, "ERT");
390 os << "\nstatus collapsed\n";
391 newcontext.check_layout(os);
392 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
394 os << "\n\\backslash\n";
398 // make sure that our comment is the last thing on the line
399 newcontext.new_paragraph(os);
400 newcontext.check_layout(os);
401 newcontext.check_end_layout(os);
406 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
408 isLayout(string const name) : name_(name) {}
409 bool operator()(LyXLayout_ptr const & ptr) const {
410 return ptr->latexname() == name_;
417 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
420 LyXTextClass::const_iterator beg = textclass.begin();
421 LyXTextClass::const_iterator end = textclass.end();
423 LyXTextClass::const_iterator
424 it = std::find_if(beg, end, isLayout(name));
426 return (it == end) ? LyXLayout_ptr() : *it;
430 void eat_whitespace(Parser &, ostream &, Context &, bool);
433 void output_command_layout(ostream & os, Parser & p, bool outer,
434 Context & parent_context,
435 LyXLayout_ptr newlayout)
437 parent_context.check_end_layout(os);
438 Context context(true, parent_context.textclass, newlayout,
439 parent_context.layout, parent_context.font);
440 if (parent_context.deeper_paragraph) {
441 // We are beginning a nested environment after a
442 // deeper paragraph inside the outer list environment.
443 // Therefore we don't need to output a "begin deeper".
444 context.need_end_deeper = true;
446 context.check_deeper(os);
447 context.check_layout(os);
448 if (context.layout->optionalargs > 0) {
449 eat_whitespace(p, os, context, false);
450 if (p.next_token().character() == '[') {
451 p.get_token(); // eat '['
452 begin_inset(os, "OptArg\n");
453 os << "status collapsed\n\n";
454 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
456 eat_whitespace(p, os, context, false);
459 parse_text(p, os, FLAG_ITEM, outer, context);
460 context.check_end_layout(os);
461 if (parent_context.deeper_paragraph) {
462 // We must suppress the "end deeper" because we
463 // suppressed the "begin deeper" above.
464 context.need_end_deeper = false;
466 context.check_end_deeper(os);
467 // We don't need really a new paragraph, but
468 // we must make sure that the next item gets a \begin_layout.
469 parent_context.new_paragraph(os);
474 * Output a space if necessary.
475 * This function gets called for every whitespace token.
477 * We have three cases here:
478 * 1. A space must be suppressed. Example: The lyxcode case below
479 * 2. A space may be suppressed. Example: Spaces before "\par"
480 * 3. A space must not be suppressed. Example: A space between two words
482 * We currently handle only 1. and 3 and from 2. only the case of
483 * spaces before newlines as a side effect.
485 * 2. could be used to suppress as many spaces as possible. This has two effects:
486 * - Reimporting LyX generated LaTeX files changes almost no whitespace
487 * - Superflous whitespace from non LyX generated LaTeX files is removed.
488 * The drawback is that the logic inside the function becomes
489 * complicated, and that is the reason why it is not implemented.
491 void check_space(Parser const & p, ostream & os, Context & context)
493 Token const next = p.next_token();
494 Token const curr = p.curr_token();
495 // A space before a single newline and vice versa must be ignored
496 // LyX emits a newline before \end{lyxcode}.
497 // This newline must be ignored,
498 // otherwise LyX will add an additional protected space.
499 if (next.cat() == catSpace ||
500 next.cat() == catNewline ||
501 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
504 context.check_layout(os);
510 * Parse all arguments of \p command
512 void parse_arguments(string const & command,
513 vector<ArgumentType> const & template_arguments,
514 Parser & p, ostream & os, bool outer, Context & context)
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);
540 * Check whether \p command is a known command. If yes,
541 * handle the command with all arguments.
542 * \return true if the command was parsed, false otherwise.
544 bool parse_command(string const & command, Parser & p, ostream & os,
545 bool outer, Context & context)
547 if (known_commands.find(command) != known_commands.end()) {
548 parse_arguments(command, known_commands[command], p, os,
556 /// Parses a minipage or parbox
557 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
558 Context & parent_context, bool use_parbox)
562 string height_value = "0";
563 string height_unit = "pt";
564 string height_special = "none";
566 if (p.next_token().asInput() == "[") {
567 position = p.getArg('[', ']');
568 if (position != "t" && position != "c" && position != "b") {
570 cerr << "invalid position for minipage/parbox" << endl;
572 if (p.next_token().asInput() == "[") {
573 latex_height = p.getArg('[', ']');
574 translate_box_len(latex_height, height_value, height_unit, height_special);
576 if (p.next_token().asInput() == "[") {
577 inner_pos = p.getArg('[', ']');
578 if (inner_pos != "c" && inner_pos != "t" &&
579 inner_pos != "b" && inner_pos != "s") {
580 inner_pos = position;
581 cerr << "invalid inner_pos for minipage/parbox"
589 string const latex_width = p.verbatim_item();
590 translate_len(latex_width, width_value, width_unit);
591 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
592 // LyX can't handle length variables
597 ss << "\\begin{minipage}";
598 if (!position.empty())
599 ss << '[' << position << ']';
600 if (!latex_height.empty())
601 ss << '[' << latex_height << ']';
602 if (!inner_pos.empty())
603 ss << '[' << inner_pos << ']';
604 ss << "{" << latex_width << "}";
607 handle_ert(os, ss.str(), parent_context);
608 parent_context.new_paragraph(os);
609 parse_text_in_inset(p, os, flags, outer, parent_context);
611 handle_ert(os, "}", parent_context);
613 handle_ert(os, "\\end{minipage}", parent_context);
615 // LyX does not like empty positions, so we have
616 // to set them to the LaTeX default values here.
617 if (position.empty())
619 if (inner_pos.empty())
620 inner_pos = position;
621 parent_context.check_layout(os);
622 begin_inset(os, "Box Frameless\n");
623 os << "position \"" << position << "\"\n";
624 os << "hor_pos \"c\"\n";
625 os << "has_inner_box 1\n";
626 os << "inner_pos \"" << inner_pos << "\"\n";
627 os << "use_parbox " << use_parbox << "\n";
628 os << "width \"" << width_value << width_unit << "\"\n";
629 os << "special \"none\"\n";
630 os << "height \"" << height_value << height_unit << "\"\n";
631 os << "height_special \"" << height_special << "\"\n";
632 os << "status open\n\n";
633 parse_text_in_inset(p, os, flags, outer, parent_context);
635 #ifdef PRESERVE_LAYOUT
636 // lyx puts a % after the end of the minipage
637 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
639 //handle_comment(os, "%dummy", parent_context);
642 parent_context.new_paragraph(os);
644 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
645 //handle_comment(os, "%dummy", parent_context);
648 // We add a protected space if something real follows
649 if (p.good() && p.next_token().cat() != catComment) {
650 os << "\\InsetSpace ~\n";
658 void parse_environment(Parser & p, ostream & os, bool outer,
659 Context & parent_context)
661 LyXLayout_ptr newlayout;
662 string const name = p.getArg('{', '}');
663 const bool is_starred = suffixIs(name, '*');
664 string const unstarred_name = rtrim(name, "*");
665 eat_whitespace(p, os, parent_context, false);
666 active_environments.push_back(name);
668 if (is_math_env(name)) {
669 parent_context.check_layout(os);
670 begin_inset(os, "Formula ");
671 os << "\\begin{" << name << "}";
672 parse_math(p, os, FLAG_END, MATH_MODE);
673 os << "\\end{" << name << "}";
677 else if (name == "tabular" || name == "longtable") {
678 parent_context.check_layout(os);
679 begin_inset(os, "Tabular ");
680 handle_tabular(p, os, name == "longtable", parent_context);
684 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
685 parent_context.check_layout(os);
686 begin_inset(os, "Float " + unstarred_name + "\n");
687 if (p.next_token().asInput() == "[") {
688 os << "placement " << p.getArg('[', ']') << '\n';
690 os << "wide " << convert<string>(is_starred)
691 << "\nsideways false"
692 << "\nstatus open\n\n";
693 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
695 // We don't need really a new paragraph, but
696 // we must make sure that the next item gets a \begin_layout.
697 parent_context.new_paragraph(os);
700 else if (name == "minipage")
701 parse_box(p, os, FLAG_END, outer, parent_context, false);
703 // Alignment settings
704 else if (name == "center" || name == "flushleft" || name == "flushright" ||
705 name == "centering" || name == "raggedright" || name == "raggedleft") {
706 // We must begin a new paragraph if not already done
707 if (! parent_context.atParagraphStart()) {
708 parent_context.check_end_layout(os);
709 parent_context.new_paragraph(os);
711 if (name == "flushleft" || name == "raggedright")
712 parent_context.add_extra_stuff("\\align left\n");
713 else if (name == "flushright" || name == "raggedleft")
714 parent_context.add_extra_stuff("\\align right\n");
716 parent_context.add_extra_stuff("\\align center\n");
717 parse_text(p, os, FLAG_END, outer, parent_context);
718 // Just in case the environment is empty ..
719 parent_context.extra_stuff.erase();
720 // We must begin a new paragraph to reset the alignment
721 parent_context.new_paragraph(os);
724 // The single '=' is meant here.
725 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
726 newlayout->isEnvironment()) {
727 Context context(true, parent_context.textclass, newlayout,
728 parent_context.layout, parent_context.font);
729 if (parent_context.deeper_paragraph) {
730 // We are beginning a nested environment after a
731 // deeper paragraph inside the outer list environment.
732 // Therefore we don't need to output a "begin deeper".
733 context.need_end_deeper = true;
735 parent_context.check_end_layout(os);
736 switch (context.layout->latextype) {
737 case LATEX_LIST_ENVIRONMENT:
738 context.extra_stuff = "\\labelwidthstring "
739 + p.verbatim_item() + '\n';
742 case LATEX_BIB_ENVIRONMENT:
743 p.verbatim_item(); // swallow next arg
749 context.check_deeper(os);
750 parse_text(p, os, FLAG_END, outer, context);
751 context.check_end_layout(os);
752 if (parent_context.deeper_paragraph) {
753 // We must suppress the "end deeper" because we
754 // suppressed the "begin deeper" above.
755 context.need_end_deeper = false;
757 context.check_end_deeper(os);
758 parent_context.new_paragraph(os);
761 else if (name == "appendix") {
762 // This is no good latex style, but it works and is used in some documents...
763 parent_context.check_end_layout(os);
764 Context context(true, parent_context.textclass, parent_context.layout,
765 parent_context.layout, parent_context.font);
766 context.check_layout(os);
767 os << "\\start_of_appendix\n";
768 parse_text(p, os, FLAG_END, outer, context);
769 context.check_end_layout(os);
772 else if (name == "comment") {
773 parent_context.check_layout(os);
774 begin_inset(os, "Note Comment\n");
775 os << "status open\n";
776 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
780 else if (name == "lyxgreyedout") {
781 parent_context.check_layout(os);
782 begin_inset(os, "Note Greyedout\n");
783 os << "status open\n";
784 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
788 else if (name == "tabbing") {
789 // We need to remember that we have to handle '\=' specially
790 handle_ert(os, "\\begin{" + name + "}", parent_context);
791 // FIXME: Try whether parse_text instead of parse_text_snippet
792 // works. Then no manual layout checking would be needed.
793 parent_context.check_end_layout(os);
794 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer,
796 parent_context.need_layout = true;
797 handle_ert(os, "\\end{" + name + "}", parent_context);
800 else if (known_environments.find(name) != known_environments.end()) {
801 vector<ArgumentType> arguments = known_environments[name];
802 // The last "argument" denotes wether we may translate the
803 // environment contents to LyX
804 // The default required if no argument is given makes us
805 // compatible with the reLyXre environment.
806 ArgumentType contents = arguments.empty() ?
809 if (!arguments.empty())
810 arguments.pop_back();
811 parse_arguments("\\begin{" + name + "}", arguments, p, os,
812 outer, parent_context);
813 if (contents == verbatim)
814 handle_ert(os, p.verbatimEnvironment(name),
817 // FIXME: Try whether parse_text instead of
818 // parse_text_snippet works. Then no manual layout
819 // checking would be needed.
820 parent_context.check_end_layout(os);
821 parse_text_snippet(p, os, FLAG_END, outer,
823 parent_context.need_layout = true;
825 handle_ert(os, "\\end{" + name + "}", parent_context);
829 handle_ert(os, "\\begin{" + name + "}", parent_context);
830 // FIXME: Try whether parse_text instead of parse_text_snippet
831 // works. Then no manual layout checking would be needed.
832 parent_context.check_end_layout(os);
833 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
834 parent_context.need_layout = true;
835 handle_ert(os, "\\end{" + name + "}", parent_context);
838 active_environments.pop_back();
844 /// parses a comment and outputs it to \p os.
845 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
847 BOOST_ASSERT(t.cat() == catComment);
848 if (!t.cs().empty()) {
849 context.check_layout(os);
850 handle_comment(os, '%' + t.cs(), context);
851 if (p.next_token().cat() == catNewline) {
852 // A newline after a comment line starts a new
854 if(!context.atParagraphStart()) {
855 // Only start a new paragraph if not already
856 // done (we might get called recursively)
857 context.new_paragraph(os);
859 eat_whitespace(p, os, context, true);
869 * Reads spaces and comments until the first non-space, non-comment token.
870 * New paragraphs (double newlines or \\par) are handled like simple spaces
871 * if \p eatParagraph is true.
872 * Spaces are skipped, but comments are written to \p os.
874 void eat_whitespace(Parser & p, ostream & os, Context & context,
878 Token const & t = p.get_token();
879 if (t.cat() == catComment)
880 parse_comment(p, os, t, context);
881 else if ((! eatParagraph && p.isParagraph()) ||
882 (t.cat() != catSpace && t.cat() != catNewline)) {
891 * Set a font attribute, parse text and reset the font attribute.
892 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
893 * \param currentvalue Current value of the attribute. Is set to the new
894 * value during parsing.
895 * \param newvalue New value of the attribute
897 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
898 Context & context, string const & attribute,
899 string & currentvalue, string const & newvalue)
901 context.check_layout(os);
902 string oldvalue = currentvalue;
903 currentvalue = newvalue;
904 os << '\n' << attribute << ' ' << newvalue << "\n";
905 parse_text_snippet(p, os, flags, outer, context);
906 currentvalue = oldvalue;
907 os << '\n' << attribute << ' ' << oldvalue << "\n";
911 /// get the arguments of a natbib or jurabib citation command
912 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
914 // We need to distinguish "" and "[]", so we can't use p.getOpt().
916 // text before the citation
918 // text after the citation
919 string after = p.getFullOpt();
921 if (!after.empty()) {
922 before = p.getFullOpt();
923 if (natbibOrder && !before.empty())
924 std::swap(before, after);
926 return std::make_pair(before, after);
930 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
931 string const normalize_filename(string const & name)
933 Parser p(trim(name, "\""));
936 Token const & t = p.get_token();
937 if (t.cat() != catEscape)
939 else if (t.cs() == "lyxdot") {
940 // This is used by LyX for simple dots in relative
944 } else if (t.cs() == "space") {
954 /// Convert \p name from TeX convention (relative to master file) to LyX
955 /// convention (relative to .lyx file) if it is relative
956 void fix_relative_filename(string & name)
958 if (lyx::support::AbsolutePath(name))
960 name = MakeRelPath(MakeAbsPath(name, getMasterFilePath()),
961 getParentFilePath());
964 } // anonymous namespace
967 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
970 LyXLayout_ptr newlayout;
971 // Store the latest bibliographystyle (needed for bibtex inset)
972 string bibliographystyle;
973 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
974 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
976 Token const & t = p.get_token();
979 cerr << "t: " << t << " flags: " << flags << "\n";
982 if (flags & FLAG_ITEM) {
983 if (t.cat() == catSpace)
987 if (t.cat() == catBegin) {
988 // skip the brace and collect everything to the next matching
990 flags |= FLAG_BRACE_LAST;
994 // handle only this single token, leave the loop if done
998 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1004 if (t.cat() == catMath) {
1005 // we are inside some text mode thingy, so opening new math is allowed
1006 context.check_layout(os);
1007 begin_inset(os, "Formula ");
1008 Token const & n = p.get_token();
1009 if (n.cat() == catMath && outer) {
1010 // TeX's $$...$$ syntax for displayed math
1012 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1014 p.get_token(); // skip the second '$' token
1016 // simple $...$ stuff
1019 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1025 else if (t.cat() == catSuper || t.cat() == catSub)
1026 cerr << "catcode " << t << " illegal in text mode\n";
1028 // Basic support for english quotes. This should be
1029 // extended to other quotes, but is not so easy (a
1030 // left english quote is the same as a right german
1032 else if (t.asInput() == "`"
1033 && p.next_token().asInput() == "`") {
1034 context.check_layout(os);
1035 begin_inset(os, "Quotes ");
1041 else if (t.asInput() == "'"
1042 && p.next_token().asInput() == "'") {
1043 context.check_layout(os);
1044 begin_inset(os, "Quotes ");
1051 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1052 check_space(p, os, context);
1054 else if (t.cat() == catLetter ||
1055 t.cat() == catOther ||
1056 t.cat() == catAlign ||
1057 t.cat() == catParameter) {
1058 // This translates "&" to "\\&" which may be wrong...
1059 context.check_layout(os);
1060 os << t.character();
1063 else if (p.isParagraph()) {
1064 context.new_paragraph(os);
1065 eat_whitespace(p, os, context, true);
1068 else if (t.cat() == catActive) {
1069 context.check_layout(os);
1070 if (t.character() == '~') {
1071 if (context.layout->free_spacing)
1074 os << "\\InsetSpace ~\n";
1076 os << t.character();
1079 else if (t.cat() == catBegin) {
1080 context.check_layout(os);
1081 // special handling of font attribute changes
1082 Token const prev = p.prev_token();
1083 Token const next = p.next_token();
1084 Font const oldFont = context.font;
1085 string const s = parse_text(p, FLAG_BRACE_LAST, outer,
1087 context.font = oldFont;
1088 if (s.empty() && (p.next_token().character() == '`' ||
1089 (prev.character() == '-' &&
1090 p.next_token().character() == '-')))
1091 ; // ignore it in {}`` or -{}-
1092 else if (s == "[" || s == "]" || s == "*")
1094 else if (is_known(next.cs(), known_sizes)) {
1095 // s will change the size, so we must reset
1098 if (!context.atParagraphStart())
1100 << context.font.size << "\n";
1101 } else if (is_known(next.cs(), known_font_families)) {
1102 // s will change the font family, so we must
1105 if (!context.atParagraphStart())
1107 << context.font.family << "\n";
1108 } else if (is_known(next.cs(), known_font_series)) {
1109 // s will change the font series, so we must
1112 if (!context.atParagraphStart())
1114 << context.font.series << "\n";
1115 } else if (is_known(next.cs(), known_font_shapes)) {
1116 // s will change the font shape, so we must
1119 if (!context.atParagraphStart())
1121 << context.font.shape << "\n";
1122 } else if (is_known(next.cs(), known_old_font_families) ||
1123 is_known(next.cs(), known_old_font_series) ||
1124 is_known(next.cs(), known_old_font_shapes)) {
1125 // s will change the font family, series
1126 // and shape, so we must reset it here
1128 if (!context.atParagraphStart())
1130 << context.font.family
1132 << context.font.series
1134 << context.font.shape << "\n";
1136 handle_ert(os, "{", context, false);
1137 // s will end the current layout and begin a
1138 // new one if necessary
1140 handle_ert(os, "}", context);
1144 else if (t.cat() == catEnd) {
1145 if (flags & FLAG_BRACE_LAST) {
1148 cerr << "stray '}' in text\n";
1149 handle_ert(os, "}", context);
1152 else if (t.cat() == catComment)
1153 parse_comment(p, os, t, context);
1156 // control sequences
1159 else if (t.cs() == "(") {
1160 context.check_layout(os);
1161 begin_inset(os, "Formula");
1163 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1168 else if (t.cs() == "[") {
1169 context.check_layout(os);
1170 begin_inset(os, "Formula");
1172 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1177 else if (t.cs() == "begin")
1178 parse_environment(p, os, outer, context);
1180 else if (t.cs() == "end") {
1181 if (flags & FLAG_END) {
1182 // eat environment name
1183 string const name = p.getArg('{', '}');
1184 if (name != active_environment())
1185 cerr << "\\end{" + name + "} does not match \\begin{"
1186 + active_environment() + "}\n";
1189 p.error("found 'end' unexpectedly");
1192 else if (t.cs() == "item") {
1195 bool optarg = false;
1196 if (p.next_token().character() == '[') {
1197 p.get_token(); // eat '['
1198 Context newcontext(false, context.textclass);
1199 newcontext.font = context.font;
1200 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
1204 context.check_layout(os);
1206 if (context.layout->labeltype != LABEL_MANUAL) {
1207 // lyx does not support \item[\mybullet]
1208 // in itemize environments
1209 handle_ert(os, "[", context);
1211 handle_ert(os, "]", context);
1212 } else if (!s.empty()) {
1213 // The space is needed to separate the
1214 // item from the rest of the sentence.
1216 eat_whitespace(p, os, context, false);
1221 else if (t.cs() == "bibitem") {
1223 context.check_layout(os);
1226 os << '{' << p.verbatim_item() << '}' << "\n";
1229 else if (t.cs() == "def") {
1230 context.check_layout(os);
1231 eat_whitespace(p, os, context, false);
1232 string name = p.get_token().cs();
1233 while (p.next_token().cat() != catBegin)
1234 name += p.get_token().asString();
1235 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1238 else if (t.cs() == "noindent") {
1240 context.add_extra_stuff("\\noindent\n");
1243 else if (t.cs() == "appendix") {
1244 context.add_extra_stuff("\\start_of_appendix\n");
1245 // We need to start a new paragraph. Otherwise the
1246 // appendix in 'bla\appendix\chapter{' would start
1248 context.new_paragraph(os);
1249 // We need to make sure that the paragraph is
1250 // generated even if it is empty. Otherwise the
1251 // appendix in '\par\appendix\par\chapter{' would
1253 context.check_layout(os);
1254 // FIXME: This is a hack to prevent paragraph
1255 // deletion if it is empty. Handle this better!
1257 "%dummy comment inserted by tex2lyx to "
1258 "ensure that this paragraph is not empty",
1260 // Both measures above may generate an additional
1261 // empty paragraph, but that does not hurt, because
1262 // whitespace does not matter here.
1263 eat_whitespace(p, os, context, true);
1266 // Must attempt to parse "Section*" before "Section".
1267 else if ((p.next_token().asInput() == "*") &&
1268 // The single '=' is meant here.
1269 (newlayout = findLayout(context.textclass,
1270 t.cs() + '*')).get() &&
1271 newlayout->isCommand()) {
1273 output_command_layout(os, p, outer, context, newlayout);
1277 // The single '=' is meant here.
1278 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
1279 newlayout->isCommand()) {
1280 output_command_layout(os, p, outer, context, newlayout);
1284 else if (t.cs() == "includegraphics") {
1285 bool const clip = p.next_token().asInput() == "*";
1288 map<string, string> opts = split_map(p.getArg('[', ']'));
1290 opts["clip"] = string();
1291 string name = normalize_filename(p.verbatim_item());
1293 string const path = getMasterFilePath();
1294 // We want to preserve relative / absolute filenames,
1295 // therefore path is only used for testing
1296 if (!fs::exists(MakeAbsPath(name, path))) {
1297 // The file extension is probably missing.
1298 // Now try to find it out.
1299 string const dvips_name =
1300 find_file(name, path,
1301 known_dvips_graphics_formats);
1302 string const pdftex_name =
1303 find_file(name, path,
1304 known_pdftex_graphics_formats);
1305 if (!dvips_name.empty()) {
1306 if (!pdftex_name.empty()) {
1307 cerr << "This file contains the "
1309 "\"\\includegraphics{"
1311 "However, files\n\""
1312 << dvips_name << "\" and\n\""
1313 << pdftex_name << "\"\n"
1314 "both exist, so I had to make a "
1315 "choice and took the first one.\n"
1316 "Please move the unwanted one "
1317 "someplace else and try again\n"
1318 "if my choice was wrong."
1322 } else if (!pdftex_name.empty())
1326 if (fs::exists(MakeAbsPath(name, path)))
1327 fix_relative_filename(name);
1329 cerr << "Warning: Could not find graphics file '"
1330 << name << "'." << endl;
1332 context.check_layout(os);
1333 begin_inset(os, "Graphics ");
1334 os << "\n\tfilename " << name << '\n';
1335 if (opts.find("width") != opts.end())
1337 << translate_len(opts["width"]) << '\n';
1338 if (opts.find("height") != opts.end())
1340 << translate_len(opts["height"]) << '\n';
1341 if (opts.find("scale") != opts.end()) {
1342 istringstream iss(opts["scale"]);
1346 os << "\tscale " << val << '\n';
1348 if (opts.find("angle") != opts.end())
1349 os << "\trotateAngle "
1350 << opts["angle"] << '\n';
1351 if (opts.find("origin") != opts.end()) {
1353 string const opt = opts["origin"];
1354 if (opt.find('l') != string::npos) ss << "left";
1355 if (opt.find('r') != string::npos) ss << "right";
1356 if (opt.find('c') != string::npos) ss << "center";
1357 if (opt.find('t') != string::npos) ss << "Top";
1358 if (opt.find('b') != string::npos) ss << "Bottom";
1359 if (opt.find('B') != string::npos) ss << "Baseline";
1360 if (!ss.str().empty())
1361 os << "\trotateOrigin " << ss.str() << '\n';
1363 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1365 if (opts.find("keepaspectratio") != opts.end())
1366 os << "\tkeepAspectRatio\n";
1367 if (opts.find("clip") != opts.end())
1369 if (opts.find("draft") != opts.end())
1371 if (opts.find("bb") != opts.end())
1372 os << "\tBoundingBox "
1373 << opts["bb"] << '\n';
1374 int numberOfbbOptions = 0;
1375 if (opts.find("bbllx") != opts.end())
1376 numberOfbbOptions++;
1377 if (opts.find("bblly") != opts.end())
1378 numberOfbbOptions++;
1379 if (opts.find("bburx") != opts.end())
1380 numberOfbbOptions++;
1381 if (opts.find("bbury") != opts.end())
1382 numberOfbbOptions++;
1383 if (numberOfbbOptions == 4)
1384 os << "\tBoundingBox "
1385 << opts["bbllx"] << opts["bblly"]
1386 << opts["bburx"] << opts["bbury"] << '\n';
1387 else if (numberOfbbOptions > 0)
1388 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1389 numberOfbbOptions = 0;
1390 if (opts.find("natwidth") != opts.end())
1391 numberOfbbOptions++;
1392 if (opts.find("natheight") != opts.end())
1393 numberOfbbOptions++;
1394 if (numberOfbbOptions == 2)
1395 os << "\tBoundingBox 0bp 0bp "
1396 << opts["natwidth"] << opts["natheight"] << '\n';
1397 else if (numberOfbbOptions > 0)
1398 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1399 ostringstream special;
1400 if (opts.find("hiresbb") != opts.end())
1401 special << "hiresbb,";
1402 if (opts.find("trim") != opts.end())
1404 if (opts.find("viewport") != opts.end())
1405 special << "viewport=" << opts["viewport"] << ',';
1406 if (opts.find("totalheight") != opts.end())
1407 special << "totalheight=" << opts["totalheight"] << ',';
1408 if (opts.find("type") != opts.end())
1409 special << "type=" << opts["type"] << ',';
1410 if (opts.find("ext") != opts.end())
1411 special << "ext=" << opts["ext"] << ',';
1412 if (opts.find("read") != opts.end())
1413 special << "read=" << opts["read"] << ',';
1414 if (opts.find("command") != opts.end())
1415 special << "command=" << opts["command"] << ',';
1416 string s_special = special.str();
1417 if (!s_special.empty()) {
1418 // We had special arguments. Remove the trailing ','.
1419 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1421 // TODO: Handle the unknown settings better.
1422 // Warn about invalid options.
1423 // Check whether some option was given twice.
1427 else if (t.cs() == "footnote" ||
1428 (t.cs() == "thanks" && context.layout->intitle)) {
1430 context.check_layout(os);
1431 begin_inset(os, "Foot\n");
1432 os << "status collapsed\n\n";
1433 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1437 else if (t.cs() == "marginpar") {
1439 context.check_layout(os);
1440 begin_inset(os, "Marginal\n");
1441 os << "status collapsed\n\n";
1442 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1446 else if (t.cs() == "ensuremath") {
1448 context.check_layout(os);
1449 Context newcontext(false, context.textclass);
1450 newcontext.font = context.font;
1451 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1452 if (s == "±" || s == "³" || s == "²" || s == "µ")
1455 handle_ert(os, "\\ensuremath{" + s + "}",
1459 else if (t.cs() == "hfill") {
1460 context.check_layout(os);
1461 os << "\n\\hfill\n";
1466 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1467 // FIXME: Somehow prevent title layouts if
1468 // "maketitle" was not found
1470 skip_braces(p); // swallow this
1473 else if (t.cs() == "tableofcontents") {
1475 context.check_layout(os);
1476 begin_inset(os, "LatexCommand \\tableofcontents\n");
1478 skip_braces(p); // swallow this
1481 else if (t.cs() == "listoffigures") {
1483 context.check_layout(os);
1484 begin_inset(os, "FloatList figure\n");
1486 skip_braces(p); // swallow this
1489 else if (t.cs() == "listoftables") {
1491 context.check_layout(os);
1492 begin_inset(os, "FloatList table\n");
1494 skip_braces(p); // swallow this
1497 else if (t.cs() == "listof") {
1498 p.skip_spaces(true);
1499 string const name = p.get_token().asString();
1500 if (context.textclass.floats().typeExist(name)) {
1501 context.check_layout(os);
1502 begin_inset(os, "FloatList ");
1505 p.get_token(); // swallow second arg
1507 handle_ert(os, "\\listof{" + name + "}", context);
1510 else if (t.cs() == "textrm")
1511 parse_text_attributes(p, os, FLAG_ITEM, outer,
1512 context, "\\family",
1513 context.font.family, "roman");
1515 else if (t.cs() == "textsf")
1516 parse_text_attributes(p, os, FLAG_ITEM, outer,
1517 context, "\\family",
1518 context.font.family, "sans");
1520 else if (t.cs() == "texttt")
1521 parse_text_attributes(p, os, FLAG_ITEM, outer,
1522 context, "\\family",
1523 context.font.family, "typewriter");
1525 else if (t.cs() == "textmd")
1526 parse_text_attributes(p, os, FLAG_ITEM, outer,
1527 context, "\\series",
1528 context.font.series, "medium");
1530 else if (t.cs() == "textbf")
1531 parse_text_attributes(p, os, FLAG_ITEM, outer,
1532 context, "\\series",
1533 context.font.series, "bold");
1535 else if (t.cs() == "textup")
1536 parse_text_attributes(p, os, FLAG_ITEM, outer,
1538 context.font.shape, "up");
1540 else if (t.cs() == "textit")
1541 parse_text_attributes(p, os, FLAG_ITEM, outer,
1543 context.font.shape, "italic");
1545 else if (t.cs() == "textsl")
1546 parse_text_attributes(p, os, FLAG_ITEM, outer,
1548 context.font.shape, "slanted");
1550 else if (t.cs() == "textsc")
1551 parse_text_attributes(p, os, FLAG_ITEM, outer,
1553 context.font.shape, "smallcaps");
1555 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1556 context.check_layout(os);
1557 Font oldFont = context.font;
1558 context.font.init();
1559 context.font.size = oldFont.size;
1560 os << "\n\\family " << context.font.family << "\n";
1561 os << "\n\\series " << context.font.series << "\n";
1562 os << "\n\\shape " << context.font.shape << "\n";
1563 if (t.cs() == "textnormal") {
1564 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1565 output_font_change(os, context.font, oldFont);
1566 context.font = oldFont;
1568 eat_whitespace(p, os, context, false);
1571 else if (t.cs() == "underbar") {
1572 // Do NOT handle \underline.
1573 // \underbar cuts through y, g, q, p etc.,
1574 // \underline does not.
1575 context.check_layout(os);
1576 os << "\n\\bar under\n";
1577 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1578 os << "\n\\bar default\n";
1581 else if (t.cs() == "emph" || t.cs() == "noun") {
1582 context.check_layout(os);
1583 os << "\n\\" << t.cs() << " on\n";
1584 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1585 os << "\n\\" << t.cs() << " default\n";
1588 else if (use_natbib &&
1589 is_known(t.cs(), known_natbib_commands) &&
1590 ((t.cs() != "citefullauthor" &&
1591 t.cs() != "citeyear" &&
1592 t.cs() != "citeyearpar") ||
1593 p.next_token().asInput() != "*")) {
1594 context.check_layout(os);
1596 // \citet[before][after]{a} \citet[after][before]{a}
1597 // \citet[before][]{a} \citet[][before]{a}
1598 // \citet[after]{a} \citet[after]{a}
1599 // \citet{a} \citet{a}
1600 string command = '\\' + t.cs();
1601 if (p.next_token().asInput() == "*") {
1605 if (command == "\\citefullauthor")
1606 // alternative name for "\\citeauthor*"
1607 command = "\\citeauthor*";
1609 // text before the citation
1611 // text after the citation
1614 boost::tie(before, after) = getCiteArguments(p, true);
1615 if (command == "\\cite") {
1616 // \cite without optional argument means
1617 // \citet, \cite with at least one optional
1618 // argument means \citep.
1619 if (before.empty() && after.empty())
1620 command = "\\citet";
1622 command = "\\citep";
1624 if (before.empty() && after == "[]")
1625 // avoid \citet[]{a}
1627 else if (before == "[]" && after == "[]") {
1628 // avoid \citet[][]{a}
1632 begin_inset(os, "LatexCommand ");
1633 os << command << after << before
1634 << '{' << p.verbatim_item() << "}\n";
1638 else if (use_jurabib &&
1639 is_known(t.cs(), known_jurabib_commands)) {
1640 context.check_layout(os);
1641 string const command = '\\' + t.cs();
1642 char argumentOrder = '\0';
1643 vector<string> const & options = used_packages["jurabib"];
1644 if (std::find(options.begin(), options.end(),
1645 "natbiborder") != options.end())
1646 argumentOrder = 'n';
1647 else if (std::find(options.begin(), options.end(),
1648 "jurabiborder") != options.end())
1649 argumentOrder = 'j';
1651 // text before the citation
1653 // text after the citation
1656 boost::tie(before, after) =
1657 getCiteArguments(p, argumentOrder != 'j');
1658 string const citation = p.verbatim_item();
1659 if (!before.empty() && argumentOrder == '\0') {
1660 cerr << "Warning: Assuming argument order "
1661 "of jurabib version 0.6 for\n'"
1662 << command << before << after << '{'
1663 << citation << "}'.\n"
1664 "Add 'jurabiborder' to the jurabib "
1665 "package options if you used an\n"
1666 "earlier jurabib version." << endl;
1668 begin_inset(os, "LatexCommand ");
1669 os << command << after << before
1670 << '{' << citation << "}\n";
1674 else if (is_known(t.cs(), known_latex_commands)) {
1675 // This needs to be after the check for natbib and
1676 // jurabib commands, because "cite" has different
1677 // arguments with natbib and jurabib.
1678 context.check_layout(os);
1679 begin_inset(os, "LatexCommand ");
1680 os << '\\' << t.cs();
1681 // lyx cannot handle newlines in a latex command
1682 // FIXME: Move the substitution into parser::getOpt()?
1683 os << subst(p.getOpt(), "\n", " ");
1684 os << subst(p.getOpt(), "\n", " ");
1685 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1689 else if (is_known(t.cs(), known_quotes)) {
1690 char const * const * where = is_known(t.cs(), known_quotes);
1691 context.check_layout(os);
1692 begin_inset(os, "Quotes ");
1693 os << known_coded_quotes[where - known_quotes];
1695 // LyX adds {} after the quote, so we have to eat
1696 // spaces here if there are any before a possible
1698 eat_whitespace(p, os, context, false);
1702 else if (is_known(t.cs(), known_sizes)) {
1703 char const * const * where = is_known(t.cs(), known_sizes);
1704 context.check_layout(os);
1705 Font const oldFont = context.font;
1706 context.font.size = known_coded_sizes[where - known_sizes];
1707 output_font_change(os, oldFont, context.font);
1708 eat_whitespace(p, os, context, false);
1711 else if (is_known(t.cs(), known_font_families)) {
1712 char const * const * where =
1713 is_known(t.cs(), known_font_families);
1714 context.check_layout(os);
1715 Font const oldFont = context.font;
1716 context.font.family =
1717 known_coded_font_families[where - known_font_families];
1718 output_font_change(os, oldFont, context.font);
1719 eat_whitespace(p, os, context, false);
1722 else if (is_known(t.cs(), known_font_series)) {
1723 char const * const * where =
1724 is_known(t.cs(), known_font_series);
1725 context.check_layout(os);
1726 Font const oldFont = context.font;
1727 context.font.series =
1728 known_coded_font_series[where - known_font_series];
1729 output_font_change(os, oldFont, context.font);
1730 eat_whitespace(p, os, context, false);
1733 else if (is_known(t.cs(), known_font_shapes)) {
1734 char const * const * where =
1735 is_known(t.cs(), known_font_shapes);
1736 context.check_layout(os);
1737 Font const oldFont = context.font;
1738 context.font.shape =
1739 known_coded_font_shapes[where - known_font_shapes];
1740 output_font_change(os, oldFont, context.font);
1741 eat_whitespace(p, os, context, false);
1743 else if (is_known(t.cs(), known_old_font_families)) {
1744 char const * const * where =
1745 is_known(t.cs(), known_old_font_families);
1746 context.check_layout(os);
1747 Font const oldFont = context.font;
1748 context.font.init();
1749 context.font.size = oldFont.size;
1750 context.font.family =
1751 known_coded_font_families[where - known_old_font_families];
1752 output_font_change(os, oldFont, context.font);
1753 eat_whitespace(p, os, context, false);
1756 else if (is_known(t.cs(), known_old_font_series)) {
1757 char const * const * where =
1758 is_known(t.cs(), known_old_font_series);
1759 context.check_layout(os);
1760 Font const oldFont = context.font;
1761 context.font.init();
1762 context.font.size = oldFont.size;
1763 context.font.series =
1764 known_coded_font_series[where - known_old_font_series];
1765 output_font_change(os, oldFont, context.font);
1766 eat_whitespace(p, os, context, false);
1769 else if (is_known(t.cs(), known_old_font_shapes)) {
1770 char const * const * where =
1771 is_known(t.cs(), known_old_font_shapes);
1772 context.check_layout(os);
1773 Font const oldFont = context.font;
1774 context.font.init();
1775 context.font.size = oldFont.size;
1776 context.font.shape =
1777 known_coded_font_shapes[where - known_old_font_shapes];
1778 output_font_change(os, oldFont, context.font);
1779 eat_whitespace(p, os, context, false);
1782 else if (t.cs() == "LyX" || t.cs() == "TeX"
1783 || t.cs() == "LaTeX") {
1784 context.check_layout(os);
1786 skip_braces(p); // eat {}
1789 else if (t.cs() == "LaTeXe") {
1790 context.check_layout(os);
1792 skip_braces(p); // eat {}
1795 else if (t.cs() == "ldots") {
1796 context.check_layout(os);
1798 os << "\\SpecialChar \\ldots{}\n";
1801 else if (t.cs() == "lyxarrow") {
1802 context.check_layout(os);
1803 os << "\\SpecialChar \\menuseparator\n";
1807 else if (t.cs() == "textcompwordmark") {
1808 context.check_layout(os);
1809 os << "\\SpecialChar \\textcompwordmark{}\n";
1813 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1814 context.check_layout(os);
1815 os << "\\SpecialChar \\@.\n";
1819 else if (t.cs() == "-") {
1820 context.check_layout(os);
1821 os << "\\SpecialChar \\-\n";
1824 else if (t.cs() == "textasciitilde") {
1825 context.check_layout(os);
1830 else if (t.cs() == "textasciicircum") {
1831 context.check_layout(os);
1836 else if (t.cs() == "textbackslash") {
1837 context.check_layout(os);
1838 os << "\n\\backslash\n";
1842 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1843 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1845 context.check_layout(os);
1849 else if (t.cs() == "char") {
1850 context.check_layout(os);
1851 if (p.next_token().character() == '`') {
1853 if (p.next_token().cs() == "\"") {
1858 handle_ert(os, "\\char`", context);
1861 handle_ert(os, "\\char", context);
1865 else if (t.cs() == "\"") {
1866 context.check_layout(os);
1867 string const name = p.verbatim_item();
1868 if (name == "a") os << 'ä';
1869 else if (name == "o") os << 'ö';
1870 else if (name == "u") os << 'ü';
1871 else if (name == "A") os << 'Ä';
1872 else if (name == "O") os << 'Ö';
1873 else if (name == "U") os << 'Ü';
1874 else handle_ert(os, "\"{" + name + "}", context);
1877 // Problem: \= creates a tabstop inside the tabbing environment
1878 // and else an accent. In the latter case we really would want
1879 // \={o} instead of \= o.
1880 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1881 handle_ert(os, t.asInput(), context);
1883 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1884 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1885 // we need the trim as the LyX parser chokes on such spaces
1886 context.check_layout(os);
1887 os << "\n\\i \\" << t.cs() << "{"
1888 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1891 else if (t.cs() == "ss") {
1892 context.check_layout(os);
1894 skip_braces(p); // eat {}
1897 else if (t.cs() == "i" || t.cs() == "j") {
1898 context.check_layout(os);
1899 os << "\\" << t.cs() << ' ';
1900 skip_braces(p); // eat {}
1903 else if (t.cs() == "\\") {
1904 context.check_layout(os);
1905 string const next = p.next_token().asInput();
1907 handle_ert(os, "\\\\" + p.getOpt(), context);
1908 else if (next == "*") {
1910 handle_ert(os, "\\\\*" + p.getOpt(), context);
1913 os << "\n\\newline\n";
1917 else if (t.cs() == "input" || t.cs() == "include"
1918 || t.cs() == "verbatiminput") {
1919 string name = '\\' + t.cs();
1920 if (t.cs() == "verbatiminput"
1921 && p.next_token().asInput() == "*")
1922 name += p.get_token().asInput();
1923 context.check_layout(os);
1924 begin_inset(os, "Include ");
1925 string filename(normalize_filename(p.getArg('{', '}')));
1926 string const path = getMasterFilePath();
1927 // We want to preserve relative / absolute filenames,
1928 // therefore path is only used for testing
1929 if (t.cs() == "include" &&
1930 !fs::exists(MakeAbsPath(filename, path))) {
1931 // The file extension is probably missing.
1932 // Now try to find it out.
1933 string const tex_name =
1934 find_file(filename, path,
1935 known_tex_extensions);
1936 if (!tex_name.empty())
1937 filename = tex_name;
1939 if (fs::exists(MakeAbsPath(filename, path))) {
1940 string const abstexname =
1941 MakeAbsPath(filename, path);
1942 string const abslyxname =
1943 ChangeExtension(abstexname, ".lyx");
1944 fix_relative_filename(filename);
1945 string const lyxname =
1946 ChangeExtension(filename, ".lyx");
1947 if (t.cs() != "verbatiminput" &&
1948 tex2lyx(abstexname, abslyxname)) {
1949 os << name << '{' << lyxname << "}\n";
1951 os << name << '{' << filename << "}\n";
1954 cerr << "Warning: Could not find included file '"
1955 << filename << "'." << endl;
1956 os << name << '{' << filename << "}\n";
1958 os << "preview false\n";
1962 else if (t.cs() == "fancyhead") {
1963 context.check_layout(os);
1965 ss << "\\fancyhead";
1967 ss << '{' << p.verbatim_item() << "}\n";
1968 handle_ert(os, ss.str(), context);
1971 else if (t.cs() == "bibliographystyle") {
1972 // store new bibliographystyle
1973 bibliographystyle = p.verbatim_item();
1974 // output new bibliographystyle.
1975 // This is only necessary if used in some other macro than \bibliography.
1976 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1979 else if (t.cs() == "bibliography") {
1980 context.check_layout(os);
1981 begin_inset(os, "LatexCommand ");
1983 // Do we have a bibliographystyle set?
1984 if (!bibliographystyle.empty()) {
1985 os << '[' << bibliographystyle << ']';
1987 os << '{' << p.verbatim_item() << "}\n";
1991 else if (t.cs() == "parbox")
1992 parse_box(p, os, FLAG_ITEM, outer, context, true);
1994 else if (t.cs() == "smallskip" ||
1995 t.cs() == "medskip" ||
1996 t.cs() == "bigskip" ||
1997 t.cs() == "vfill") {
1998 context.check_layout(os);
1999 begin_inset(os, "VSpace ");
2005 else if (t.cs() == "newcommand" ||
2006 t.cs() == "providecommand" ||
2007 t.cs() == "renewcommand") {
2008 // these could be handled by parse_command(), but
2009 // we need to call add_known_command() here.
2010 string name = t.asInput();
2011 if (p.next_token().asInput() == "*") {
2012 // Starred form. Eat '*'
2016 string const command = p.verbatim_item();
2017 string const opt1 = p.getOpt();
2018 string const opt2 = p.getFullOpt();
2019 add_known_command(command, opt1, !opt2.empty());
2020 string const ert = name + '{' + command + '}' +
2022 '{' + p.verbatim_item() + '}';
2023 handle_ert(os, ert, context);
2026 else if (t.cs() == "vspace") {
2027 bool starred = false;
2028 if (p.next_token().asInput() == "*") {
2032 string const length = p.verbatim_item();
2035 bool valid = splitLatexLength(length, valstring, unit);
2036 bool known_vspace = false;
2037 bool known_unit = false;
2040 istringstream iss(valstring);
2043 if (unit == "\\smallskipamount") {
2045 known_vspace = true;
2046 } else if (unit == "\\medskipamount") {
2048 known_vspace = true;
2049 } else if (unit == "\\bigskipamount") {
2051 known_vspace = true;
2052 } else if (unit == "\\fill") {
2054 known_vspace = true;
2057 if (!known_vspace) {
2058 switch (unitFromString(unit)) {
2079 if (known_unit || known_vspace) {
2080 // Literal length or known variable
2081 context.check_layout(os);
2082 begin_inset(os, "VSpace ");
2090 // LyX can't handle other length variables in Inset VSpace
2091 string name = t.asInput();
2096 handle_ert(os, name + '{' + unit + '}', context);
2097 else if (value == -1.0)
2098 handle_ert(os, name + "{-" + unit + '}', context);
2100 handle_ert(os, name + '{' + valstring + unit + '}', context);
2102 handle_ert(os, name + '{' + length + '}', context);
2107 //cerr << "#: " << t << " mode: " << mode << endl;
2108 // heuristic: read up to next non-nested space
2110 string s = t.asInput();
2111 string z = p.verbatim_item();
2112 while (p.good() && z != " " && z.size()) {
2113 //cerr << "read: " << z << endl;
2115 z = p.verbatim_item();
2117 cerr << "found ERT: " << s << endl;
2118 handle_ert(os, s + ' ', context);
2120 string name = t.asInput();
2121 if (p.next_token().asInput() == "*") {
2122 // Starred commands like \vspace*{}
2123 p.get_token(); // Eat '*'
2126 if (! parse_command(name, p, os, outer, context))
2127 handle_ert(os, name, context);
2130 if (flags & FLAG_LEAVE) {
2131 flags &= ~FLAG_LEAVE;