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>
35 using support::changeExtension;
36 using support::FileName;
37 using support::makeAbsPath;
38 using support::makeRelPath;
40 using support::suffixIs;
41 using support::contains;
49 using std::ostringstream;
50 using std::istringstream;
54 namespace fs = boost::filesystem;
57 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
58 Context const & context)
60 Context newcontext(true, context.textclass);
61 newcontext.font = context.font;
62 parse_text(p, os, flags, outer, newcontext);
63 newcontext.check_end_layout(os);
69 /// parses a paragraph snippet, useful for example for \\emph{...}
70 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
73 Context newcontext(context);
74 // Don't inherit the extra stuff
75 newcontext.extra_stuff.clear();
76 parse_text(p, os, flags, outer, newcontext);
77 // Make sure that we don't create invalid .lyx files
78 context.need_layout = newcontext.need_layout;
79 context.need_end_layout = newcontext.need_end_layout;
84 * Thin wrapper around parse_text_snippet() using a string.
86 * We completely ignore \c context.need_layout and \c context.need_end_layout,
87 * because our return value is not used directly (otherwise the stream version
88 * of parse_text_snippet() could be used). That means that the caller needs
89 * to do layout management manually.
90 * This is intended to parse text that does not create any layout changes.
92 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
95 Context newcontext(context);
96 newcontext.need_layout = false;
97 newcontext.need_end_layout = false;
98 newcontext.new_layout_allowed = false;
99 // Avoid warning by Context::~Context()
100 newcontext.extra_stuff.clear();
102 parse_text_snippet(p, os, flags, outer, newcontext);
107 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
108 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
112 * We can't put these into known_latex_commands because the argument order
113 * is reversed in lyx if there are 2 arguments.
114 * The starred forms are also known.
116 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
117 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
118 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
122 * We can't put these into known_latex_commands because the argument order
123 * is reversed in lyx if there are 2 arguments.
124 * No starred form other than "cite*" known.
126 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
127 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
128 // jurabib commands not (yet) supported by LyX:
130 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
131 // "footciteauthor", "footciteyear", "footciteyearpar",
132 "citefield", "citetitle", "cite*", 0 };
134 /// LaTeX names for quotes
135 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
136 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
138 /// the same as known_quotes with .lyx names
139 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
140 "grd", "gls", "fls", "frs", 0};
142 /// LaTeX names for font sizes
143 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
144 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
146 /// the same as known_sizes with .lyx names
147 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
148 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
150 /// LaTeX 2.09 names for font families
151 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
153 /// LaTeX names for font families
154 char const * const known_font_families[] = { "rmfamily", "sffamily",
157 /// the same as known_old_font_families and known_font_families with .lyx names
158 char const * const known_coded_font_families[] = { "roman", "sans",
161 /// LaTeX 2.09 names for font series
162 char const * const known_old_font_series[] = { "bf", 0};
164 /// LaTeX names for font series
165 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
167 /// the same as known_old_font_series and known_font_series with .lyx names
168 char const * const known_coded_font_series[] = { "bold", "medium", 0};
170 /// LaTeX 2.09 names for font shapes
171 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
173 /// LaTeX names for font shapes
174 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
177 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
178 char const * const known_coded_font_shapes[] = { "italic", "slanted",
179 "smallcaps", "up", 0};
182 * Graphics file extensions known by the dvips driver of the graphics package.
183 * These extensions are used to complete the filename of an included
184 * graphics file if it does not contain an extension.
185 * The order must be the same that latex uses to find a file, because we
186 * will use the first extension that matches.
187 * This is only an approximation for the common cases. If we would want to
188 * do it right in all cases, we would need to know which graphics driver is
189 * used and know the extensions of every driver of the graphics package.
191 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
192 "ps.gz", "eps.Z", "ps.Z", 0};
195 * Graphics file extensions known by the pdftex driver of the graphics package.
196 * \sa known_dvips_graphics_formats
198 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
202 * Known file extensions for TeX files as used by \\include.
204 char const * const known_tex_extensions[] = {"tex", 0};
206 /// spaces known by InsetSpace
207 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
208 "qquad", "enspace", "enskip", "negthinspace", 0};
210 /// the same as known_spaces with .lyx names
211 char const * const known_coded_spaces[] = { "space{}", "space{}",
212 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
213 "negthinspace{}", 0};
216 /// splits "x=z, y=b" into a map
217 map<string, string> split_map(string const & s)
219 map<string, string> res;
222 for (size_t i = 0; i < v.size(); ++i) {
223 size_t const pos = v[i].find('=');
224 string const index = v[i].substr(0, pos);
225 string const value = v[i].substr(pos + 1, string::npos);
226 res[trim(index)] = trim(value);
233 * Split a LaTeX length into value and unit.
234 * The latter can be a real unit like "pt", or a latex length variable
235 * like "\textwidth". The unit may contain additional stuff like glue
236 * lengths, but we don't care, because such lengths are ERT anyway.
237 * \returns true if \p value and \p unit are valid.
239 bool splitLatexLength(string const & len, string & value, string & unit)
243 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
244 //'4,5' is a valid LaTeX length number. Change it to '4.5'
245 string const length = subst(len, ',', '.');
246 if (i == string::npos)
249 if (len[0] == '\\') {
250 // We had something like \textwidth without a factor
256 value = trim(string(length, 0, i));
260 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
261 if (contains(len, '\\'))
262 unit = trim(string(len, i));
264 unit = lyx::support::lowercase(trim(string(len, i)));
269 /// A simple function to translate a latex length to something lyx can
270 /// understand. Not perfect, but rather best-effort.
271 bool translate_len(string const & length, string & valstring, string & unit)
273 if (!splitLatexLength(length, valstring, unit))
275 // LyX uses percent values
277 istringstream iss(valstring);
282 string const percentval = oss.str();
284 if (unit.empty() || unit[0] != '\\')
286 string::size_type const i = unit.find(' ');
287 string const endlen = (i == string::npos) ? string() : string(unit, i);
288 if (unit == "\\textwidth") {
289 valstring = percentval;
290 unit = "text%" + endlen;
291 } else if (unit == "\\columnwidth") {
292 valstring = percentval;
293 unit = "col%" + endlen;
294 } else if (unit == "\\paperwidth") {
295 valstring = percentval;
296 unit = "page%" + endlen;
297 } else if (unit == "\\linewidth") {
298 valstring = percentval;
299 unit = "line%" + endlen;
300 } else if (unit == "\\paperheight") {
301 valstring = percentval;
302 unit = "pheight%" + endlen;
303 } else if (unit == "\\textheight") {
304 valstring = percentval;
305 unit = "theight%" + endlen;
313 string translate_len(string const & length)
317 if (translate_len(length, value, unit))
319 // If the input is invalid, return what we have.
327 * Translates a LaTeX length into \p value, \p unit and
328 * \p special parts suitable for a box inset.
329 * The difference from translate_len() is that a box inset knows about
330 * some special "units" that are stored in \p special.
332 void translate_box_len(string const & length, string & value, string & unit, string & special)
334 if (translate_len(length, value, unit)) {
335 if (unit == "\\height" || unit == "\\depth" ||
336 unit == "\\totalheight" || unit == "\\width") {
337 special = unit.substr(1);
338 // The unit is not used, but LyX requires a dummy setting
351 * Find a file with basename \p name in path \p path and an extension
354 string find_file(string const & name, string const & path,
355 char const * const * extensions)
357 for (char const * const * what = extensions; *what; ++what) {
358 // We don't use ChangeExtension() because it does the wrong
359 // thing if name contains a dot.
360 string const trial = name + '.' + (*what);
361 if (fs::exists(FileName(makeAbsPath(trial, path)).toFilesystemEncoding()))
368 void begin_inset(ostream & os, string const & name)
370 os << "\n\\begin_inset " << name;
374 void end_inset(ostream & os)
376 os << "\n\\end_inset\n\n";
380 void skip_braces(Parser & p)
382 if (p.next_token().cat() != catBegin)
385 if (p.next_token().cat() == catEnd) {
393 void handle_ert(ostream & os, string const & s, Context & context)
395 // We must have a valid layout before outputting the ERT inset.
396 context.check_layout(os);
397 Context newcontext(true, context.textclass);
398 begin_inset(os, "ERT");
399 os << "\nstatus collapsed\n";
400 newcontext.check_layout(os);
401 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
403 os << "\n\\backslash\n";
404 else if (*it == '\n') {
405 newcontext.new_paragraph(os);
406 newcontext.check_layout(os);
410 newcontext.check_end_layout(os);
415 void handle_comment(ostream & os, string const & s, Context & context)
417 // TODO: Handle this better
418 Context newcontext(true, context.textclass);
419 begin_inset(os, "ERT");
420 os << "\nstatus collapsed\n";
421 newcontext.check_layout(os);
422 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
424 os << "\n\\backslash\n";
428 // make sure that our comment is the last thing on the line
429 newcontext.new_paragraph(os);
430 newcontext.check_layout(os);
431 newcontext.check_end_layout(os);
436 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
438 isLayout(string const name) : name_(name) {}
439 bool operator()(LyXLayout_ptr const & ptr) const {
440 return ptr->latexname() == name_;
447 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
450 LyXTextClass::const_iterator beg = textclass.begin();
451 LyXTextClass::const_iterator end = textclass.end();
453 LyXTextClass::const_iterator
454 it = std::find_if(beg, end, isLayout(name));
456 return (it == end) ? LyXLayout_ptr() : *it;
460 void eat_whitespace(Parser &, ostream &, Context &, bool);
463 void output_command_layout(ostream & os, Parser & p, bool outer,
464 Context & parent_context,
465 LyXLayout_ptr newlayout)
467 parent_context.check_end_layout(os);
468 Context context(true, parent_context.textclass, newlayout,
469 parent_context.layout, parent_context.font);
470 if (parent_context.deeper_paragraph) {
471 // We are beginning a nested environment after a
472 // deeper paragraph inside the outer list environment.
473 // Therefore we don't need to output a "begin deeper".
474 context.need_end_deeper = true;
476 context.check_deeper(os);
477 context.check_layout(os);
478 if (context.layout->optionalargs > 0) {
479 eat_whitespace(p, os, context, false);
480 if (p.next_token().character() == '[') {
481 p.get_token(); // eat '['
482 begin_inset(os, "OptArg\n");
483 os << "status collapsed\n\n";
484 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
486 eat_whitespace(p, os, context, false);
489 parse_text(p, os, FLAG_ITEM, outer, context);
490 context.check_end_layout(os);
491 if (parent_context.deeper_paragraph) {
492 // We must suppress the "end deeper" because we
493 // suppressed the "begin deeper" above.
494 context.need_end_deeper = false;
496 context.check_end_deeper(os);
497 // We don't need really a new paragraph, but
498 // we must make sure that the next item gets a \begin_layout.
499 parent_context.new_paragraph(os);
504 * Output a space if necessary.
505 * This function gets called for every whitespace token.
507 * We have three cases here:
508 * 1. A space must be suppressed. Example: The lyxcode case below
509 * 2. A space may be suppressed. Example: Spaces before "\par"
510 * 3. A space must not be suppressed. Example: A space between two words
512 * We currently handle only 1. and 3 and from 2. only the case of
513 * spaces before newlines as a side effect.
515 * 2. could be used to suppress as many spaces as possible. This has two effects:
516 * - Reimporting LyX generated LaTeX files changes almost no whitespace
517 * - Superflous whitespace from non LyX generated LaTeX files is removed.
518 * The drawback is that the logic inside the function becomes
519 * complicated, and that is the reason why it is not implemented.
521 void check_space(Parser const & p, ostream & os, Context & context)
523 Token const next = p.next_token();
524 Token const curr = p.curr_token();
525 // A space before a single newline and vice versa must be ignored
526 // LyX emits a newline before \end{lyxcode}.
527 // This newline must be ignored,
528 // otherwise LyX will add an additional protected space.
529 if (next.cat() == catSpace ||
530 next.cat() == catNewline ||
531 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
534 context.check_layout(os);
540 * Parse all arguments of \p command
542 void parse_arguments(string const & command,
543 vector<ArgumentType> const & template_arguments,
544 Parser & p, ostream & os, bool outer, Context & context)
546 string ert = command;
547 size_t no_arguments = template_arguments.size();
548 for (size_t i = 0; i < no_arguments; ++i) {
549 switch (template_arguments[i]) {
551 // This argument contains regular LaTeX
552 handle_ert(os, ert + '{', context);
553 eat_whitespace(p, os, context, false);
554 parse_text(p, os, FLAG_ITEM, outer, context);
558 // This argument may contain special characters
559 ert += '{' + p.verbatim_item() + '}';
566 handle_ert(os, ert, context);
571 * Check whether \p command is a known command. If yes,
572 * handle the command with all arguments.
573 * \return true if the command was parsed, false otherwise.
575 bool parse_command(string const & command, Parser & p, ostream & os,
576 bool outer, Context & context)
578 if (known_commands.find(command) != known_commands.end()) {
579 parse_arguments(command, known_commands[command], p, os,
587 /// Parses a minipage or parbox
588 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
589 Context & parent_context, bool use_parbox)
593 string height_value = "0";
594 string height_unit = "pt";
595 string height_special = "none";
597 if (p.next_token().asInput() == "[") {
598 position = p.getArg('[', ']');
599 if (position != "t" && position != "c" && position != "b") {
601 cerr << "invalid position for minipage/parbox" << endl;
603 if (p.next_token().asInput() == "[") {
604 latex_height = p.getArg('[', ']');
605 translate_box_len(latex_height, height_value, height_unit, height_special);
607 if (p.next_token().asInput() == "[") {
608 inner_pos = p.getArg('[', ']');
609 if (inner_pos != "c" && inner_pos != "t" &&
610 inner_pos != "b" && inner_pos != "s") {
611 inner_pos = position;
612 cerr << "invalid inner_pos for minipage/parbox"
620 string const latex_width = p.verbatim_item();
621 translate_len(latex_width, width_value, width_unit);
622 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
623 // LyX can't handle length variables
628 ss << "\\begin{minipage}";
629 if (!position.empty())
630 ss << '[' << position << ']';
631 if (!latex_height.empty())
632 ss << '[' << latex_height << ']';
633 if (!inner_pos.empty())
634 ss << '[' << inner_pos << ']';
635 ss << "{" << latex_width << "}";
638 handle_ert(os, ss.str(), parent_context);
639 parent_context.new_paragraph(os);
640 parse_text_in_inset(p, os, flags, outer, parent_context);
642 handle_ert(os, "}", parent_context);
644 handle_ert(os, "\\end{minipage}", parent_context);
646 // LyX does not like empty positions, so we have
647 // to set them to the LaTeX default values here.
648 if (position.empty())
650 if (inner_pos.empty())
651 inner_pos = position;
652 parent_context.check_layout(os);
653 begin_inset(os, "Box Frameless\n");
654 os << "position \"" << position << "\"\n";
655 os << "hor_pos \"c\"\n";
656 os << "has_inner_box 1\n";
657 os << "inner_pos \"" << inner_pos << "\"\n";
658 os << "use_parbox " << use_parbox << "\n";
659 os << "width \"" << width_value << width_unit << "\"\n";
660 os << "special \"none\"\n";
661 os << "height \"" << height_value << height_unit << "\"\n";
662 os << "height_special \"" << height_special << "\"\n";
663 os << "status open\n\n";
664 parse_text_in_inset(p, os, flags, outer, parent_context);
666 #ifdef PRESERVE_LAYOUT
667 // lyx puts a % after the end of the minipage
668 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
670 //handle_comment(os, "%dummy", parent_context);
673 parent_context.new_paragraph(os);
675 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
676 //handle_comment(os, "%dummy", parent_context);
679 // We add a protected space if something real follows
680 if (p.good() && p.next_token().cat() != catComment) {
681 os << "\\InsetSpace ~\n";
689 /// parse an unknown environment
690 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
691 unsigned flags, bool outer,
692 Context & parent_context)
694 if (name == "tabbing")
695 // We need to remember that we have to handle '\=' specially
696 flags |= FLAG_TABBING;
698 // We need to translate font changes and paragraphs inside the
699 // environment to ERT if we have a non standard font.
700 // Otherwise things like
701 // \large\begin{foo}\huge bar\end{foo}
703 bool const specialfont =
704 (parent_context.font != parent_context.normalfont);
705 bool const new_layout_allowed = parent_context.new_layout_allowed;
707 parent_context.new_layout_allowed = false;
708 handle_ert(os, "\\begin{" + name + "}", parent_context);
709 parse_text_snippet(p, os, flags, outer, parent_context);
710 handle_ert(os, "\\end{" + name + "}", parent_context);
712 parent_context.new_layout_allowed = new_layout_allowed;
716 void parse_environment(Parser & p, ostream & os, bool outer,
717 Context & parent_context)
719 LyXLayout_ptr newlayout;
720 string const name = p.getArg('{', '}');
721 const bool is_starred = suffixIs(name, '*');
722 string const unstarred_name = rtrim(name, "*");
723 active_environments.push_back(name);
725 if (is_math_env(name)) {
726 parent_context.check_layout(os);
727 begin_inset(os, "Formula ");
728 os << "\\begin{" << name << "}";
729 parse_math(p, os, FLAG_END, MATH_MODE);
730 os << "\\end{" << name << "}";
734 else if (name == "tabular" || name == "longtable") {
735 eat_whitespace(p, os, parent_context, false);
736 parent_context.check_layout(os);
737 begin_inset(os, "Tabular ");
738 handle_tabular(p, os, name == "longtable", parent_context);
743 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
744 eat_whitespace(p, os, parent_context, false);
745 parent_context.check_layout(os);
746 begin_inset(os, "Float " + unstarred_name + "\n");
747 if (p.next_token().asInput() == "[") {
748 os << "placement " << p.getArg('[', ']') << '\n';
750 os << "wide " << convert<string>(is_starred)
751 << "\nsideways false"
752 << "\nstatus open\n\n";
753 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
755 // We don't need really a new paragraph, but
756 // we must make sure that the next item gets a \begin_layout.
757 parent_context.new_paragraph(os);
761 else if (name == "minipage") {
762 eat_whitespace(p, os, parent_context, false);
763 parse_box(p, os, FLAG_END, outer, parent_context, false);
767 else if (name == "comment") {
768 eat_whitespace(p, os, parent_context, false);
769 parent_context.check_layout(os);
770 begin_inset(os, "Note Comment\n");
771 os << "status open\n";
772 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
777 else if (name == "lyxgreyedout") {
778 eat_whitespace(p, os, parent_context, false);
779 parent_context.check_layout(os);
780 begin_inset(os, "Note Greyedout\n");
781 os << "status open\n";
782 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
787 else if (!parent_context.new_layout_allowed)
788 parse_unknown_environment(p, name, os, FLAG_END, outer,
791 // Alignment settings
792 else if (name == "center" || name == "flushleft" || name == "flushright" ||
793 name == "centering" || name == "raggedright" || name == "raggedleft") {
794 eat_whitespace(p, os, parent_context, false);
795 // We must begin a new paragraph if not already done
796 if (! parent_context.atParagraphStart()) {
797 parent_context.check_end_layout(os);
798 parent_context.new_paragraph(os);
800 if (name == "flushleft" || name == "raggedright")
801 parent_context.add_extra_stuff("\\align left\n");
802 else if (name == "flushright" || name == "raggedleft")
803 parent_context.add_extra_stuff("\\align right\n");
805 parent_context.add_extra_stuff("\\align center\n");
806 parse_text(p, os, FLAG_END, outer, parent_context);
807 // Just in case the environment is empty ..
808 parent_context.extra_stuff.erase();
809 // We must begin a new paragraph to reset the alignment
810 parent_context.new_paragraph(os);
814 // The single '=' is meant here.
815 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
816 newlayout->isEnvironment()) {
817 eat_whitespace(p, os, parent_context, false);
818 Context context(true, parent_context.textclass, newlayout,
819 parent_context.layout, parent_context.font);
820 if (parent_context.deeper_paragraph) {
821 // We are beginning a nested environment after a
822 // deeper paragraph inside the outer list environment.
823 // Therefore we don't need to output a "begin deeper".
824 context.need_end_deeper = true;
826 parent_context.check_end_layout(os);
827 switch (context.layout->latextype) {
828 case LATEX_LIST_ENVIRONMENT:
829 context.extra_stuff = "\\labelwidthstring "
830 + p.verbatim_item() + '\n';
833 case LATEX_BIB_ENVIRONMENT:
834 p.verbatim_item(); // swallow next arg
840 context.check_deeper(os);
841 parse_text(p, os, FLAG_END, outer, context);
842 context.check_end_layout(os);
843 if (parent_context.deeper_paragraph) {
844 // We must suppress the "end deeper" because we
845 // suppressed the "begin deeper" above.
846 context.need_end_deeper = false;
848 context.check_end_deeper(os);
849 parent_context.new_paragraph(os);
853 else if (name == "appendix") {
854 // This is no good latex style, but it works and is used in some documents...
855 eat_whitespace(p, os, parent_context, false);
856 parent_context.check_end_layout(os);
857 Context context(true, parent_context.textclass, parent_context.layout,
858 parent_context.layout, parent_context.font);
859 context.check_layout(os);
860 os << "\\start_of_appendix\n";
861 parse_text(p, os, FLAG_END, outer, context);
862 context.check_end_layout(os);
866 else if (known_environments.find(name) != known_environments.end()) {
867 vector<ArgumentType> arguments = known_environments[name];
868 // The last "argument" denotes wether we may translate the
869 // environment contents to LyX
870 // The default required if no argument is given makes us
871 // compatible with the reLyXre environment.
872 ArgumentType contents = arguments.empty() ?
875 if (!arguments.empty())
876 arguments.pop_back();
877 // See comment in parse_unknown_environment()
878 bool const specialfont =
879 (parent_context.font != parent_context.normalfont);
880 bool const new_layout_allowed =
881 parent_context.new_layout_allowed;
883 parent_context.new_layout_allowed = false;
884 parse_arguments("\\begin{" + name + "}", arguments, p, os,
885 outer, parent_context);
886 if (contents == verbatim)
887 handle_ert(os, p.verbatimEnvironment(name),
890 parse_text_snippet(p, os, FLAG_END, outer,
892 handle_ert(os, "\\end{" + name + "}", parent_context);
894 parent_context.new_layout_allowed = new_layout_allowed;
898 parse_unknown_environment(p, name, os, FLAG_END, outer,
901 active_environments.pop_back();
905 /// parses a comment and outputs it to \p os.
906 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
908 BOOST_ASSERT(t.cat() == catComment);
909 if (!t.cs().empty()) {
910 context.check_layout(os);
911 handle_comment(os, '%' + t.cs(), context);
912 if (p.next_token().cat() == catNewline) {
913 // A newline after a comment line starts a new
915 if (context.new_layout_allowed) {
916 if(!context.atParagraphStart())
917 // Only start a new paragraph if not already
918 // done (we might get called recursively)
919 context.new_paragraph(os);
921 handle_ert(os, "\n", context);
922 eat_whitespace(p, os, context, true);
932 * Reads spaces and comments until the first non-space, non-comment token.
933 * New paragraphs (double newlines or \\par) are handled like simple spaces
934 * if \p eatParagraph is true.
935 * Spaces are skipped, but comments are written to \p os.
937 void eat_whitespace(Parser & p, ostream & os, Context & context,
941 Token const & t = p.get_token();
942 if (t.cat() == catComment)
943 parse_comment(p, os, t, context);
944 else if ((! eatParagraph && p.isParagraph()) ||
945 (t.cat() != catSpace && t.cat() != catNewline)) {
954 * Set a font attribute, parse text and reset the font attribute.
955 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
956 * \param currentvalue Current value of the attribute. Is set to the new
957 * value during parsing.
958 * \param newvalue New value of the attribute
960 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
961 Context & context, string const & attribute,
962 string & currentvalue, string const & newvalue)
964 context.check_layout(os);
965 string const oldvalue = currentvalue;
966 currentvalue = newvalue;
967 os << '\n' << attribute << ' ' << newvalue << "\n";
968 parse_text_snippet(p, os, flags, outer, context);
969 context.check_layout(os);
970 os << '\n' << attribute << ' ' << oldvalue << "\n";
971 currentvalue = oldvalue;
975 /// get the arguments of a natbib or jurabib citation command
976 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
978 // We need to distinguish "" and "[]", so we can't use p.getOpt().
980 // text before the citation
982 // text after the citation
983 string after = p.getFullOpt();
985 if (!after.empty()) {
986 before = p.getFullOpt();
987 if (natbibOrder && !before.empty())
988 std::swap(before, after);
990 return std::make_pair(before, after);
994 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
995 string const normalize_filename(string const & name)
997 Parser p(trim(name, "\""));
1000 Token const & t = p.get_token();
1001 if (t.cat() != catEscape)
1003 else if (t.cs() == "lyxdot") {
1004 // This is used by LyX for simple dots in relative
1008 } else if (t.cs() == "space") {
1018 /// Convert \p name from TeX convention (relative to master file) to LyX
1019 /// convention (relative to .lyx file) if it is relative
1020 void fix_relative_filename(string & name)
1022 if (lyx::support::absolutePath(name))
1024 name = makeRelPath(makeAbsPath(name, getMasterFilePath()),
1025 getParentFilePath());
1029 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1030 void parse_noweb(Parser & p, ostream & os, Context & context)
1032 // assemble the rest of the keyword
1036 Token const & t = p.get_token();
1037 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1040 scrap = (p.good() && p.next_token().asInput() == "=");
1042 name += p.get_token().asInput();
1045 name += t.asInput();
1048 if (!scrap || !context.new_layout_allowed ||
1049 !context.textclass.hasLayout("Scrap")) {
1050 cerr << "Warning: Could not interpret '" << name
1051 << "'. Ignoring it." << endl;
1055 context.check_end_layout(os);
1056 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1057 newcontext.check_layout(os);
1060 Token const & t = p.get_token();
1061 // We abuse the parser a bit, because this is no TeX syntax
1063 if (t.cat() == catEscape)
1064 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1066 os << subst(t.asInput(), "\n", "\n\\newline\n");
1067 // The scrap chunk is ended by an @ at the beginning of a line.
1068 // After the @ the line may contain a comment and/or
1069 // whitespace, but nothing else.
1070 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1071 (p.next_token().cat() == catSpace ||
1072 p.next_token().cat() == catNewline ||
1073 p.next_token().cat() == catComment)) {
1074 while (p.good() && p.next_token().cat() == catSpace)
1075 os << p.get_token().asInput();
1076 if (p.next_token().cat() == catComment)
1077 // The comment includes a final '\n'
1078 os << p.get_token().asInput();
1080 if (p.next_token().cat() == catNewline)
1087 newcontext.check_end_layout(os);
1090 } // anonymous namespace
1093 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1096 LyXLayout_ptr newlayout;
1097 // Store the latest bibliographystyle (needed for bibtex inset)
1098 string bibliographystyle;
1099 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1100 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1102 Token const & t = p.get_token();
1105 cerr << "t: " << t << " flags: " << flags << "\n";
1108 if (flags & FLAG_ITEM) {
1109 if (t.cat() == catSpace)
1112 flags &= ~FLAG_ITEM;
1113 if (t.cat() == catBegin) {
1114 // skip the brace and collect everything to the next matching
1116 flags |= FLAG_BRACE_LAST;
1120 // handle only this single token, leave the loop if done
1121 flags |= FLAG_LEAVE;
1124 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1130 if (t.cat() == catMath) {
1131 // we are inside some text mode thingy, so opening new math is allowed
1132 context.check_layout(os);
1133 begin_inset(os, "Formula ");
1134 Token const & n = p.get_token();
1135 if (n.cat() == catMath && outer) {
1136 // TeX's $$...$$ syntax for displayed math
1138 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1140 p.get_token(); // skip the second '$' token
1142 // simple $...$ stuff
1145 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1151 else if (t.cat() == catSuper || t.cat() == catSub)
1152 cerr << "catcode " << t << " illegal in text mode\n";
1154 // Basic support for english quotes. This should be
1155 // extended to other quotes, but is not so easy (a
1156 // left english quote is the same as a right german
1158 else if (t.asInput() == "`"
1159 && p.next_token().asInput() == "`") {
1160 context.check_layout(os);
1161 begin_inset(os, "Quotes ");
1167 else if (t.asInput() == "'"
1168 && p.next_token().asInput() == "'") {
1169 context.check_layout(os);
1170 begin_inset(os, "Quotes ");
1177 else if (t.asInput() == "<"
1178 && p.next_token().asInput() == "<" && noweb_mode) {
1180 parse_noweb(p, os, context);
1183 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1184 check_space(p, os, context);
1186 else if (t.character() == '[' && noweb_mode &&
1187 p.next_token().character() == '[') {
1188 // These can contain underscores
1190 string const s = p.getFullOpt() + ']';
1191 if (p.next_token().character() == ']')
1194 cerr << "Warning: Inserting missing ']' in '"
1195 << s << "'." << endl;
1196 handle_ert(os, s, context);
1199 else if (t.cat() == catLetter ||
1200 t.cat() == catOther ||
1201 t.cat() == catAlign ||
1202 t.cat() == catParameter) {
1203 // This translates "&" to "\\&" which may be wrong...
1204 context.check_layout(os);
1205 os << t.character();
1208 else if (p.isParagraph()) {
1209 if (context.new_layout_allowed)
1210 context.new_paragraph(os);
1212 handle_ert(os, "\\par ", context);
1213 eat_whitespace(p, os, context, true);
1216 else if (t.cat() == catActive) {
1217 context.check_layout(os);
1218 if (t.character() == '~') {
1219 if (context.layout->free_spacing)
1222 os << "\\InsetSpace ~\n";
1224 os << t.character();
1227 else if (t.cat() == catBegin &&
1228 p.next_token().cat() == catEnd) {
1230 Token const prev = p.prev_token();
1232 if (p.next_token().character() == '`' ||
1233 (prev.character() == '-' &&
1234 p.next_token().character() == '-'))
1235 ; // ignore it in {}`` or -{}-
1237 handle_ert(os, "{}", context);
1241 else if (t.cat() == catBegin) {
1242 context.check_layout(os);
1243 // special handling of font attribute changes
1244 Token const prev = p.prev_token();
1245 Token const next = p.next_token();
1246 Font const oldFont = context.font;
1247 if (next.character() == '[' ||
1248 next.character() == ']' ||
1249 next.character() == '*') {
1251 if (p.next_token().cat() == catEnd) {
1252 os << next.character();
1256 handle_ert(os, "{", context);
1257 parse_text_snippet(p, os,
1260 handle_ert(os, "}", context);
1262 } else if (! context.new_layout_allowed) {
1263 handle_ert(os, "{", context);
1264 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1266 handle_ert(os, "}", context);
1267 } else if (is_known(next.cs(), known_sizes)) {
1268 // next will change the size, so we must
1270 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1272 if (!context.atParagraphStart())
1274 << context.font.size << "\n";
1275 } else if (is_known(next.cs(), known_font_families)) {
1276 // next will change the font family, so we
1277 // must reset it here
1278 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1280 if (!context.atParagraphStart())
1282 << context.font.family << "\n";
1283 } else if (is_known(next.cs(), known_font_series)) {
1284 // next will change the font series, so we
1285 // must reset it here
1286 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1288 if (!context.atParagraphStart())
1290 << context.font.series << "\n";
1291 } else if (is_known(next.cs(), known_font_shapes)) {
1292 // next will change the font shape, so we
1293 // must reset it here
1294 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1296 if (!context.atParagraphStart())
1298 << context.font.shape << "\n";
1299 } else if (is_known(next.cs(), known_old_font_families) ||
1300 is_known(next.cs(), known_old_font_series) ||
1301 is_known(next.cs(), known_old_font_shapes)) {
1302 // next will change the font family, series
1303 // and shape, so we must reset it here
1304 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1306 if (!context.atParagraphStart())
1308 << context.font.family
1310 << context.font.series
1312 << context.font.shape << "\n";
1314 handle_ert(os, "{", context);
1315 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1317 handle_ert(os, "}", context);
1321 else if (t.cat() == catEnd) {
1322 if (flags & FLAG_BRACE_LAST) {
1325 cerr << "stray '}' in text\n";
1326 handle_ert(os, "}", context);
1329 else if (t.cat() == catComment)
1330 parse_comment(p, os, t, context);
1333 // control sequences
1336 else if (t.cs() == "(") {
1337 context.check_layout(os);
1338 begin_inset(os, "Formula");
1340 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1345 else if (t.cs() == "[") {
1346 context.check_layout(os);
1347 begin_inset(os, "Formula");
1349 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1354 else if (t.cs() == "begin")
1355 parse_environment(p, os, outer, context);
1357 else if (t.cs() == "end") {
1358 if (flags & FLAG_END) {
1359 // eat environment name
1360 string const name = p.getArg('{', '}');
1361 if (name != active_environment())
1362 cerr << "\\end{" + name + "} does not match \\begin{"
1363 + active_environment() + "}\n";
1366 p.error("found 'end' unexpectedly");
1369 else if (t.cs() == "item") {
1372 bool optarg = false;
1373 if (p.next_token().character() == '[') {
1374 p.get_token(); // eat '['
1375 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1380 context.check_layout(os);
1381 if (context.has_item) {
1382 // An item in an unknown list-like environment
1383 // FIXME: Do this in check_layout()!
1384 context.has_item = false;
1386 handle_ert(os, "\\item", context);
1388 handle_ert(os, "\\item ", context);
1391 if (context.layout->labeltype != LABEL_MANUAL) {
1392 // lyx does not support \item[\mybullet]
1393 // in itemize environments
1394 handle_ert(os, "[", context);
1396 handle_ert(os, "]", context);
1397 } else if (!s.empty()) {
1398 // The space is needed to separate the
1399 // item from the rest of the sentence.
1401 eat_whitespace(p, os, context, false);
1406 else if (t.cs() == "bibitem") {
1408 context.check_layout(os);
1411 os << '{' << p.verbatim_item() << '}' << "\n";
1414 else if (t.cs() == "def") {
1415 context.check_layout(os);
1416 eat_whitespace(p, os, context, false);
1417 string name = p.get_token().cs();
1418 while (p.next_token().cat() != catBegin)
1419 name += p.get_token().asString();
1420 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1423 else if (t.cs() == "noindent") {
1425 context.add_extra_stuff("\\noindent\n");
1428 else if (t.cs() == "appendix") {
1429 context.add_extra_stuff("\\start_of_appendix\n");
1430 // We need to start a new paragraph. Otherwise the
1431 // appendix in 'bla\appendix\chapter{' would start
1433 context.new_paragraph(os);
1434 // We need to make sure that the paragraph is
1435 // generated even if it is empty. Otherwise the
1436 // appendix in '\par\appendix\par\chapter{' would
1438 context.check_layout(os);
1439 // FIXME: This is a hack to prevent paragraph
1440 // deletion if it is empty. Handle this better!
1442 "%dummy comment inserted by tex2lyx to "
1443 "ensure that this paragraph is not empty",
1445 // Both measures above may generate an additional
1446 // empty paragraph, but that does not hurt, because
1447 // whitespace does not matter here.
1448 eat_whitespace(p, os, context, true);
1451 // Must attempt to parse "Section*" before "Section".
1452 else if ((p.next_token().asInput() == "*") &&
1453 context.new_layout_allowed &&
1454 // The single '=' is meant here.
1455 (newlayout = findLayout(context.textclass,
1456 t.cs() + '*')).get() &&
1457 newlayout->isCommand()) {
1459 output_command_layout(os, p, outer, context, newlayout);
1463 // The single '=' is meant here.
1464 else if (context.new_layout_allowed &&
1465 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1466 newlayout->isCommand()) {
1467 output_command_layout(os, p, outer, context, newlayout);
1471 else if (t.cs() == "includegraphics") {
1472 bool const clip = p.next_token().asInput() == "*";
1475 map<string, string> opts = split_map(p.getArg('[', ']'));
1477 opts["clip"] = string();
1478 string name = normalize_filename(p.verbatim_item());
1480 string const path = getMasterFilePath();
1481 // We want to preserve relative / absolute filenames,
1482 // therefore path is only used for testing
1483 if (!fs::exists(FileName(makeAbsPath(name, path)).toFilesystemEncoding())) {
1484 // The file extension is probably missing.
1485 // Now try to find it out.
1486 string const dvips_name =
1487 find_file(name, path,
1488 known_dvips_graphics_formats);
1489 string const pdftex_name =
1490 find_file(name, path,
1491 known_pdftex_graphics_formats);
1492 if (!dvips_name.empty()) {
1493 if (!pdftex_name.empty()) {
1494 cerr << "This file contains the "
1496 "\"\\includegraphics{"
1498 "However, files\n\""
1499 << dvips_name << "\" and\n\""
1500 << pdftex_name << "\"\n"
1501 "both exist, so I had to make a "
1502 "choice and took the first one.\n"
1503 "Please move the unwanted one "
1504 "someplace else and try again\n"
1505 "if my choice was wrong."
1509 } else if (!pdftex_name.empty())
1513 if (fs::exists(FileName(makeAbsPath(name, path)).toFilesystemEncoding()))
1514 fix_relative_filename(name);
1516 cerr << "Warning: Could not find graphics file '"
1517 << name << "'." << endl;
1519 context.check_layout(os);
1520 begin_inset(os, "Graphics ");
1521 os << "\n\tfilename " << name << '\n';
1522 if (opts.find("width") != opts.end())
1524 << translate_len(opts["width"]) << '\n';
1525 if (opts.find("height") != opts.end())
1527 << translate_len(opts["height"]) << '\n';
1528 if (opts.find("scale") != opts.end()) {
1529 istringstream iss(opts["scale"]);
1533 os << "\tscale " << val << '\n';
1535 if (opts.find("angle") != opts.end())
1536 os << "\trotateAngle "
1537 << opts["angle"] << '\n';
1538 if (opts.find("origin") != opts.end()) {
1540 string const opt = opts["origin"];
1541 if (opt.find('l') != string::npos) ss << "left";
1542 if (opt.find('r') != string::npos) ss << "right";
1543 if (opt.find('c') != string::npos) ss << "center";
1544 if (opt.find('t') != string::npos) ss << "Top";
1545 if (opt.find('b') != string::npos) ss << "Bottom";
1546 if (opt.find('B') != string::npos) ss << "Baseline";
1547 if (!ss.str().empty())
1548 os << "\trotateOrigin " << ss.str() << '\n';
1550 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1552 if (opts.find("keepaspectratio") != opts.end())
1553 os << "\tkeepAspectRatio\n";
1554 if (opts.find("clip") != opts.end())
1556 if (opts.find("draft") != opts.end())
1558 if (opts.find("bb") != opts.end())
1559 os << "\tBoundingBox "
1560 << opts["bb"] << '\n';
1561 int numberOfbbOptions = 0;
1562 if (opts.find("bbllx") != opts.end())
1563 numberOfbbOptions++;
1564 if (opts.find("bblly") != opts.end())
1565 numberOfbbOptions++;
1566 if (opts.find("bburx") != opts.end())
1567 numberOfbbOptions++;
1568 if (opts.find("bbury") != opts.end())
1569 numberOfbbOptions++;
1570 if (numberOfbbOptions == 4)
1571 os << "\tBoundingBox "
1572 << opts["bbllx"] << opts["bblly"]
1573 << opts["bburx"] << opts["bbury"] << '\n';
1574 else if (numberOfbbOptions > 0)
1575 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1576 numberOfbbOptions = 0;
1577 if (opts.find("natwidth") != opts.end())
1578 numberOfbbOptions++;
1579 if (opts.find("natheight") != opts.end())
1580 numberOfbbOptions++;
1581 if (numberOfbbOptions == 2)
1582 os << "\tBoundingBox 0bp 0bp "
1583 << opts["natwidth"] << opts["natheight"] << '\n';
1584 else if (numberOfbbOptions > 0)
1585 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1586 ostringstream special;
1587 if (opts.find("hiresbb") != opts.end())
1588 special << "hiresbb,";
1589 if (opts.find("trim") != opts.end())
1591 if (opts.find("viewport") != opts.end())
1592 special << "viewport=" << opts["viewport"] << ',';
1593 if (opts.find("totalheight") != opts.end())
1594 special << "totalheight=" << opts["totalheight"] << ',';
1595 if (opts.find("type") != opts.end())
1596 special << "type=" << opts["type"] << ',';
1597 if (opts.find("ext") != opts.end())
1598 special << "ext=" << opts["ext"] << ',';
1599 if (opts.find("read") != opts.end())
1600 special << "read=" << opts["read"] << ',';
1601 if (opts.find("command") != opts.end())
1602 special << "command=" << opts["command"] << ',';
1603 string s_special = special.str();
1604 if (!s_special.empty()) {
1605 // We had special arguments. Remove the trailing ','.
1606 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1608 // TODO: Handle the unknown settings better.
1609 // Warn about invalid options.
1610 // Check whether some option was given twice.
1614 else if (t.cs() == "footnote" ||
1615 (t.cs() == "thanks" && context.layout->intitle)) {
1617 context.check_layout(os);
1618 begin_inset(os, "Foot\n");
1619 os << "status collapsed\n\n";
1620 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1624 else if (t.cs() == "marginpar") {
1626 context.check_layout(os);
1627 begin_inset(os, "Marginal\n");
1628 os << "status collapsed\n\n";
1629 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1633 else if (t.cs() == "ensuremath") {
1635 context.check_layout(os);
1636 string const s = p.verbatim_item();
1637 if (s == "±" || s == "³" || s == "²" || s == "µ")
1640 handle_ert(os, "\\ensuremath{" + s + "}",
1644 else if (t.cs() == "hfill") {
1645 context.check_layout(os);
1646 os << "\n\\hfill\n";
1651 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1652 // FIXME: Somehow prevent title layouts if
1653 // "maketitle" was not found
1655 skip_braces(p); // swallow this
1658 else if (t.cs() == "tableofcontents") {
1660 context.check_layout(os);
1661 begin_inset(os, "LatexCommand \\tableofcontents\n");
1663 skip_braces(p); // swallow this
1666 else if (t.cs() == "listoffigures") {
1668 context.check_layout(os);
1669 begin_inset(os, "FloatList figure\n");
1671 skip_braces(p); // swallow this
1674 else if (t.cs() == "listoftables") {
1676 context.check_layout(os);
1677 begin_inset(os, "FloatList table\n");
1679 skip_braces(p); // swallow this
1682 else if (t.cs() == "listof") {
1683 p.skip_spaces(true);
1684 string const name = p.get_token().asString();
1685 if (context.textclass.floats().typeExist(name)) {
1686 context.check_layout(os);
1687 begin_inset(os, "FloatList ");
1690 p.get_token(); // swallow second arg
1692 handle_ert(os, "\\listof{" + name + "}", context);
1695 else if (t.cs() == "textrm")
1696 parse_text_attributes(p, os, FLAG_ITEM, outer,
1697 context, "\\family",
1698 context.font.family, "roman");
1700 else if (t.cs() == "textsf")
1701 parse_text_attributes(p, os, FLAG_ITEM, outer,
1702 context, "\\family",
1703 context.font.family, "sans");
1705 else if (t.cs() == "texttt")
1706 parse_text_attributes(p, os, FLAG_ITEM, outer,
1707 context, "\\family",
1708 context.font.family, "typewriter");
1710 else if (t.cs() == "textmd")
1711 parse_text_attributes(p, os, FLAG_ITEM, outer,
1712 context, "\\series",
1713 context.font.series, "medium");
1715 else if (t.cs() == "textbf")
1716 parse_text_attributes(p, os, FLAG_ITEM, outer,
1717 context, "\\series",
1718 context.font.series, "bold");
1720 else if (t.cs() == "textup")
1721 parse_text_attributes(p, os, FLAG_ITEM, outer,
1723 context.font.shape, "up");
1725 else if (t.cs() == "textit")
1726 parse_text_attributes(p, os, FLAG_ITEM, outer,
1728 context.font.shape, "italic");
1730 else if (t.cs() == "textsl")
1731 parse_text_attributes(p, os, FLAG_ITEM, outer,
1733 context.font.shape, "slanted");
1735 else if (t.cs() == "textsc")
1736 parse_text_attributes(p, os, FLAG_ITEM, outer,
1738 context.font.shape, "smallcaps");
1740 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1741 context.check_layout(os);
1742 Font oldFont = context.font;
1743 context.font.init();
1744 context.font.size = oldFont.size;
1745 os << "\n\\family " << context.font.family << "\n";
1746 os << "\n\\series " << context.font.series << "\n";
1747 os << "\n\\shape " << context.font.shape << "\n";
1748 if (t.cs() == "textnormal") {
1749 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1750 output_font_change(os, context.font, oldFont);
1751 context.font = oldFont;
1753 eat_whitespace(p, os, context, false);
1756 else if (t.cs() == "underbar") {
1757 // Do NOT handle \underline.
1758 // \underbar cuts through y, g, q, p etc.,
1759 // \underline does not.
1760 context.check_layout(os);
1761 os << "\n\\bar under\n";
1762 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1763 context.check_layout(os);
1764 os << "\n\\bar default\n";
1767 else if (t.cs() == "emph" || t.cs() == "noun") {
1768 context.check_layout(os);
1769 os << "\n\\" << t.cs() << " on\n";
1770 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1771 context.check_layout(os);
1772 os << "\n\\" << t.cs() << " default\n";
1775 else if (use_natbib &&
1776 is_known(t.cs(), known_natbib_commands) &&
1777 ((t.cs() != "citefullauthor" &&
1778 t.cs() != "citeyear" &&
1779 t.cs() != "citeyearpar") ||
1780 p.next_token().asInput() != "*")) {
1781 context.check_layout(os);
1783 // \citet[before][after]{a} \citet[after][before]{a}
1784 // \citet[before][]{a} \citet[][before]{a}
1785 // \citet[after]{a} \citet[after]{a}
1786 // \citet{a} \citet{a}
1787 string command = '\\' + t.cs();
1788 if (p.next_token().asInput() == "*") {
1792 if (command == "\\citefullauthor")
1793 // alternative name for "\\citeauthor*"
1794 command = "\\citeauthor*";
1796 // text before the citation
1798 // text after the citation
1801 boost::tie(before, after) = getCiteArguments(p, true);
1802 if (command == "\\cite") {
1803 // \cite without optional argument means
1804 // \citet, \cite with at least one optional
1805 // argument means \citep.
1806 if (before.empty() && after.empty())
1807 command = "\\citet";
1809 command = "\\citep";
1811 if (before.empty() && after == "[]")
1812 // avoid \citet[]{a}
1814 else if (before == "[]" && after == "[]") {
1815 // avoid \citet[][]{a}
1819 begin_inset(os, "LatexCommand ");
1820 os << command << after << before
1821 << '{' << p.verbatim_item() << "}\n";
1825 else if (use_jurabib &&
1826 is_known(t.cs(), known_jurabib_commands)) {
1827 context.check_layout(os);
1828 string const command = '\\' + t.cs();
1829 char argumentOrder = '\0';
1830 vector<string> const & options = used_packages["jurabib"];
1831 if (std::find(options.begin(), options.end(),
1832 "natbiborder") != options.end())
1833 argumentOrder = 'n';
1834 else if (std::find(options.begin(), options.end(),
1835 "jurabiborder") != options.end())
1836 argumentOrder = 'j';
1838 // text before the citation
1840 // text after the citation
1843 boost::tie(before, after) =
1844 getCiteArguments(p, argumentOrder != 'j');
1845 string const citation = p.verbatim_item();
1846 if (!before.empty() && argumentOrder == '\0') {
1847 cerr << "Warning: Assuming argument order "
1848 "of jurabib version 0.6 for\n'"
1849 << command << before << after << '{'
1850 << citation << "}'.\n"
1851 "Add 'jurabiborder' to the jurabib "
1852 "package options if you used an\n"
1853 "earlier jurabib version." << endl;
1855 begin_inset(os, "LatexCommand ");
1856 os << command << after << before
1857 << '{' << citation << "}\n";
1861 else if (is_known(t.cs(), known_latex_commands)) {
1862 // This needs to be after the check for natbib and
1863 // jurabib commands, because "cite" has different
1864 // arguments with natbib and jurabib.
1865 context.check_layout(os);
1866 begin_inset(os, "LatexCommand ");
1867 os << '\\' << t.cs();
1868 // lyx cannot handle newlines in a latex command
1869 // FIXME: Move the substitution into parser::getOpt()?
1870 os << subst(p.getOpt(), "\n", " ");
1871 os << subst(p.getOpt(), "\n", " ");
1872 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1876 else if (is_known(t.cs(), known_quotes)) {
1877 char const * const * where = is_known(t.cs(), known_quotes);
1878 context.check_layout(os);
1879 begin_inset(os, "Quotes ");
1880 os << known_coded_quotes[where - known_quotes];
1882 // LyX adds {} after the quote, so we have to eat
1883 // spaces here if there are any before a possible
1885 eat_whitespace(p, os, context, false);
1889 else if (is_known(t.cs(), known_sizes) &&
1890 context.new_layout_allowed) {
1891 char const * const * where = is_known(t.cs(), known_sizes);
1892 context.check_layout(os);
1893 Font const oldFont = context.font;
1894 context.font.size = known_coded_sizes[where - known_sizes];
1895 output_font_change(os, oldFont, context.font);
1896 eat_whitespace(p, os, context, false);
1899 else if (is_known(t.cs(), known_font_families) &&
1900 context.new_layout_allowed) {
1901 char const * const * where =
1902 is_known(t.cs(), known_font_families);
1903 context.check_layout(os);
1904 Font const oldFont = context.font;
1905 context.font.family =
1906 known_coded_font_families[where - known_font_families];
1907 output_font_change(os, oldFont, context.font);
1908 eat_whitespace(p, os, context, false);
1911 else if (is_known(t.cs(), known_font_series) &&
1912 context.new_layout_allowed) {
1913 char const * const * where =
1914 is_known(t.cs(), known_font_series);
1915 context.check_layout(os);
1916 Font const oldFont = context.font;
1917 context.font.series =
1918 known_coded_font_series[where - known_font_series];
1919 output_font_change(os, oldFont, context.font);
1920 eat_whitespace(p, os, context, false);
1923 else if (is_known(t.cs(), known_font_shapes) &&
1924 context.new_layout_allowed) {
1925 char const * const * where =
1926 is_known(t.cs(), known_font_shapes);
1927 context.check_layout(os);
1928 Font const oldFont = context.font;
1929 context.font.shape =
1930 known_coded_font_shapes[where - known_font_shapes];
1931 output_font_change(os, oldFont, context.font);
1932 eat_whitespace(p, os, context, false);
1934 else if (is_known(t.cs(), known_old_font_families) &&
1935 context.new_layout_allowed) {
1936 char const * const * where =
1937 is_known(t.cs(), known_old_font_families);
1938 context.check_layout(os);
1939 Font const oldFont = context.font;
1940 context.font.init();
1941 context.font.size = oldFont.size;
1942 context.font.family =
1943 known_coded_font_families[where - known_old_font_families];
1944 output_font_change(os, oldFont, context.font);
1945 eat_whitespace(p, os, context, false);
1948 else if (is_known(t.cs(), known_old_font_series) &&
1949 context.new_layout_allowed) {
1950 char const * const * where =
1951 is_known(t.cs(), known_old_font_series);
1952 context.check_layout(os);
1953 Font const oldFont = context.font;
1954 context.font.init();
1955 context.font.size = oldFont.size;
1956 context.font.series =
1957 known_coded_font_series[where - known_old_font_series];
1958 output_font_change(os, oldFont, context.font);
1959 eat_whitespace(p, os, context, false);
1962 else if (is_known(t.cs(), known_old_font_shapes) &&
1963 context.new_layout_allowed) {
1964 char const * const * where =
1965 is_known(t.cs(), known_old_font_shapes);
1966 context.check_layout(os);
1967 Font const oldFont = context.font;
1968 context.font.init();
1969 context.font.size = oldFont.size;
1970 context.font.shape =
1971 known_coded_font_shapes[where - known_old_font_shapes];
1972 output_font_change(os, oldFont, context.font);
1973 eat_whitespace(p, os, context, false);
1976 else if (t.cs() == "LyX" || t.cs() == "TeX"
1977 || t.cs() == "LaTeX") {
1978 context.check_layout(os);
1980 skip_braces(p); // eat {}
1983 else if (t.cs() == "LaTeXe") {
1984 context.check_layout(os);
1986 skip_braces(p); // eat {}
1989 else if (t.cs() == "ldots") {
1990 context.check_layout(os);
1992 os << "\\SpecialChar \\ldots{}\n";
1995 else if (t.cs() == "lyxarrow") {
1996 context.check_layout(os);
1997 os << "\\SpecialChar \\menuseparator\n";
2001 else if (t.cs() == "textcompwordmark") {
2002 context.check_layout(os);
2003 os << "\\SpecialChar \\textcompwordmark{}\n";
2007 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2008 context.check_layout(os);
2009 os << "\\SpecialChar \\@.\n";
2013 else if (t.cs() == "-") {
2014 context.check_layout(os);
2015 os << "\\SpecialChar \\-\n";
2018 else if (t.cs() == "textasciitilde") {
2019 context.check_layout(os);
2024 else if (t.cs() == "textasciicircum") {
2025 context.check_layout(os);
2030 else if (t.cs() == "textbackslash") {
2031 context.check_layout(os);
2032 os << "\n\\backslash\n";
2036 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2037 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2039 context.check_layout(os);
2043 else if (t.cs() == "char") {
2044 context.check_layout(os);
2045 if (p.next_token().character() == '`') {
2047 if (p.next_token().cs() == "\"") {
2052 handle_ert(os, "\\char`", context);
2055 handle_ert(os, "\\char", context);
2059 else if (t.cs() == "verb") {
2060 context.check_layout(os);
2061 char const delimiter = p.next_token().character();
2062 string const arg = p.getArg(delimiter, delimiter);
2064 oss << "\\verb" << delimiter << arg << delimiter;
2065 handle_ert(os, oss.str(), context);
2068 else if (t.cs() == "\"") {
2069 context.check_layout(os);
2070 string const name = p.verbatim_item();
2071 if (name == "a") os << 'ä';
2072 else if (name == "o") os << 'ö';
2073 else if (name == "u") os << 'ü';
2074 else if (name == "A") os << 'Ä';
2075 else if (name == "O") os << 'Ö';
2076 else if (name == "U") os << 'Ü';
2077 else handle_ert(os, "\"{" + name + "}", context);
2080 // Problem: \= creates a tabstop inside the tabbing environment
2081 // and else an accent. In the latter case we really would want
2082 // \={o} instead of \= o.
2083 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2084 handle_ert(os, t.asInput(), context);
2086 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2087 || t.cs() == "'" || t.cs() == "`"
2088 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2089 // we need the trim as the LyX parser chokes on such spaces
2090 context.check_layout(os);
2091 os << "\n\\i \\" << t.cs() << "{"
2092 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2096 else if (t.cs() == "ss") {
2097 context.check_layout(os);
2099 skip_braces(p); // eat {}
2102 else if (t.cs() == "i" || t.cs() == "j") {
2103 context.check_layout(os);
2104 os << "\\" << t.cs() << ' ';
2105 skip_braces(p); // eat {}
2108 else if (t.cs() == "\\") {
2109 context.check_layout(os);
2110 string const next = p.next_token().asInput();
2112 handle_ert(os, "\\\\" + p.getOpt(), context);
2113 else if (next == "*") {
2115 handle_ert(os, "\\\\*" + p.getOpt(), context);
2118 os << "\n\\newline\n";
2122 else if (t.cs() == "input" || t.cs() == "include"
2123 || t.cs() == "verbatiminput") {
2124 string name = '\\' + t.cs();
2125 if (t.cs() == "verbatiminput"
2126 && p.next_token().asInput() == "*")
2127 name += p.get_token().asInput();
2128 context.check_layout(os);
2129 begin_inset(os, "Include ");
2130 string filename(normalize_filename(p.getArg('{', '}')));
2131 string const path = getMasterFilePath();
2132 // We want to preserve relative / absolute filenames,
2133 // therefore path is only used for testing
2134 if (t.cs() == "include" &&
2135 !fs::exists(FileName(makeAbsPath(filename, path)).toFilesystemEncoding())) {
2136 // The file extension is probably missing.
2137 // Now try to find it out.
2138 string const tex_name =
2139 find_file(filename, path,
2140 known_tex_extensions);
2141 if (!tex_name.empty())
2142 filename = tex_name;
2144 if (fs::exists(FileName(makeAbsPath(filename, path)).toFilesystemEncoding())) {
2145 string const abstexname =
2146 makeAbsPath(filename, path);
2147 string const abslyxname =
2148 changeExtension(abstexname, ".lyx");
2149 fix_relative_filename(filename);
2150 string const lyxname =
2151 changeExtension(filename, ".lyx");
2152 if (t.cs() != "verbatiminput" &&
2153 tex2lyx(abstexname, FileName(abslyxname))) {
2154 os << name << '{' << lyxname << "}\n";
2156 os << name << '{' << filename << "}\n";
2159 cerr << "Warning: Could not find included file '"
2160 << filename << "'." << endl;
2161 os << name << '{' << filename << "}\n";
2163 os << "preview false\n";
2167 else if (t.cs() == "bibliographystyle") {
2168 // store new bibliographystyle
2169 bibliographystyle = p.verbatim_item();
2170 // output new bibliographystyle.
2171 // This is only necessary if used in some other macro than \bibliography.
2172 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2175 else if (t.cs() == "bibliography") {
2176 context.check_layout(os);
2177 begin_inset(os, "LatexCommand ");
2179 // Do we have a bibliographystyle set?
2180 if (!bibliographystyle.empty()) {
2181 os << '[' << bibliographystyle << ']';
2183 os << '{' << p.verbatim_item() << "}\n";
2187 else if (t.cs() == "parbox")
2188 parse_box(p, os, FLAG_ITEM, outer, context, true);
2190 else if (t.cs() == "smallskip" ||
2191 t.cs() == "medskip" ||
2192 t.cs() == "bigskip" ||
2193 t.cs() == "vfill") {
2194 context.check_layout(os);
2195 begin_inset(os, "VSpace ");
2201 else if (is_known(t.cs(), known_spaces)) {
2202 char const * const * where = is_known(t.cs(), known_spaces);
2203 context.check_layout(os);
2204 begin_inset(os, "InsetSpace ");
2205 os << '\\' << known_coded_spaces[where - known_spaces]
2207 // LaTeX swallows whitespace after all spaces except
2208 // "\\,". We have to do that here, too, because LyX
2209 // adds "{}" which would make the spaces significant.
2211 eat_whitespace(p, os, context, false);
2212 // LyX adds "{}" after all spaces except "\\ " and
2213 // "\\,", so we have to remove "{}".
2214 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2215 // remove the braces after "\\,", too.
2220 else if (t.cs() == "newpage" ||
2221 t.cs() == "clearpage" ||
2222 t.cs() == "cleardoublepage") {
2223 context.check_layout(os);
2224 // FIXME: what about \\pagebreak?
2225 os << "\n\\" << t.cs() << "\n";
2226 skip_braces(p); // eat {}
2229 else if (t.cs() == "newcommand" ||
2230 t.cs() == "providecommand" ||
2231 t.cs() == "renewcommand") {
2232 // these could be handled by parse_command(), but
2233 // we need to call add_known_command() here.
2234 string name = t.asInput();
2235 if (p.next_token().asInput() == "*") {
2236 // Starred form. Eat '*'
2240 string const command = p.verbatim_item();
2241 string const opt1 = p.getOpt();
2242 string const opt2 = p.getFullOpt();
2243 add_known_command(command, opt1, !opt2.empty());
2244 string const ert = name + '{' + command + '}' +
2246 '{' + p.verbatim_item() + '}';
2247 handle_ert(os, ert, context);
2250 else if (t.cs() == "vspace") {
2251 bool starred = false;
2252 if (p.next_token().asInput() == "*") {
2256 string const length = p.verbatim_item();
2259 bool valid = splitLatexLength(length, valstring, unit);
2260 bool known_vspace = false;
2261 bool known_unit = false;
2264 istringstream iss(valstring);
2267 if (unit == "\\smallskipamount") {
2269 known_vspace = true;
2270 } else if (unit == "\\medskipamount") {
2272 known_vspace = true;
2273 } else if (unit == "\\bigskipamount") {
2275 known_vspace = true;
2276 } else if (unit == "\\fill") {
2278 known_vspace = true;
2281 if (!known_vspace) {
2282 switch (unitFromString(unit)) {
2303 if (known_unit || known_vspace) {
2304 // Literal length or known variable
2305 context.check_layout(os);
2306 begin_inset(os, "VSpace ");
2314 // LyX can't handle other length variables in Inset VSpace
2315 string name = t.asInput();
2320 handle_ert(os, name + '{' + unit + '}', context);
2321 else if (value == -1.0)
2322 handle_ert(os, name + "{-" + unit + '}', context);
2324 handle_ert(os, name + '{' + valstring + unit + '}', context);
2326 handle_ert(os, name + '{' + length + '}', context);
2331 //cerr << "#: " << t << " mode: " << mode << endl;
2332 // heuristic: read up to next non-nested space
2334 string s = t.asInput();
2335 string z = p.verbatim_item();
2336 while (p.good() && z != " " && z.size()) {
2337 //cerr << "read: " << z << endl;
2339 z = p.verbatim_item();
2341 cerr << "found ERT: " << s << endl;
2342 handle_ert(os, s + ' ', context);
2344 string name = t.asInput();
2345 if (p.next_token().asInput() == "*") {
2346 // Starred commands like \vspace*{}
2347 p.get_token(); // Eat '*'
2350 if (! parse_command(name, p, os, outer, context))
2351 handle_ert(os, name, context);
2354 if (flags & FLAG_LEAVE) {
2355 flags &= ~FLAG_LEAVE;