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 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
54 Context const & context)
56 Context newcontext(true, context.textclass);
57 newcontext.font = context.font;
58 parse_text(p, os, flags, outer, newcontext);
59 newcontext.check_end_layout(os);
65 /// parses a paragraph snippet, useful for example for \\emph{...}
66 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
69 Context newcontext(context);
70 // Don't inherit the extra stuff
71 newcontext.extra_stuff.clear();
72 parse_text(p, os, flags, outer, newcontext);
73 // Make sure that we don't create invalid .lyx files
74 context.need_layout = newcontext.need_layout;
75 context.need_end_layout = newcontext.need_end_layout;
80 * Thin wrapper around parse_text_snippet() using a string.
82 * We completely ignore \c context.need_layout and \c context.need_end_layout,
83 * because our return value is not used directly (otherwise the stream version
84 * of parse_text_snippet() could be used). That means that the caller needs
85 * to do layout management manually.
86 * This is intended to parse text that does not create any layout changes.
88 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
91 Context newcontext(context);
92 newcontext.need_layout = false;
93 newcontext.need_end_layout = false;
94 newcontext.new_layout_allowed = false;
95 // Avoid warning by Context::~Context()
96 newcontext.extra_stuff.clear();
98 parse_text_snippet(p, os, flags, outer, newcontext);
103 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
104 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
108 * We can't put these into known_latex_commands because the argument order
109 * is reversed in lyx if there are 2 arguments.
110 * The starred forms are also known.
112 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
113 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
114 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
118 * We can't put these into known_latex_commands because the argument order
119 * is reversed in lyx if there are 2 arguments.
120 * No starred form other than "cite*" known.
122 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
123 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar", "fullcite",
124 // jurabib commands not (yet) supported by LyX:
125 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
126 // "footciteauthor", "footciteyear", "footciteyearpar",
127 "citefield", "citetitle", "cite*", 0 };
129 /// LaTeX names for quotes
130 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
131 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
133 /// the same as known_quotes with .lyx names
134 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
135 "grd", "gls", "fls", "frd", 0};
137 /// LaTeX names for font sizes
138 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
139 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
141 /// the same as known_sizes with .lyx names
142 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
143 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
145 /// LaTeX 2.09 names for font families
146 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
148 /// LaTeX names for font families
149 char const * const known_font_families[] = { "rmfamily", "sffamily",
152 /// the same as known_old_font_families and known_font_families with .lyx names
153 char const * const known_coded_font_families[] = { "roman", "sans",
156 /// LaTeX 2.09 names for font series
157 char const * const known_old_font_series[] = { "bf", 0};
159 /// LaTeX names for font series
160 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
162 /// the same as known_old_font_series and known_font_series with .lyx names
163 char const * const known_coded_font_series[] = { "bold", "medium", 0};
165 /// LaTeX 2.09 names for font shapes
166 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
168 /// LaTeX names for font shapes
169 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
172 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
173 char const * const known_coded_font_shapes[] = { "italic", "slanted",
174 "smallcaps", "up", 0};
177 * Graphics file extensions known by the dvips driver of the graphics package.
178 * These extensions are used to complete the filename of an included
179 * graphics file if it does not contain an extension.
180 * The order must be the same that latex uses to find a file, because we
181 * will use the first extension that matches.
182 * This is only an approximation for the common cases. If we would want to
183 * do it right in all cases, we would need to know which graphics driver is
184 * used and know the extensions of every driver of the graphics package.
186 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
187 "ps.gz", "eps.Z", "ps.Z", 0};
190 * Graphics file extensions known by the pdftex driver of the graphics package.
191 * \sa known_dvips_graphics_formats
193 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
197 * Known file extensions for TeX files as used by \\include.
199 char const * const known_tex_extensions[] = {"tex", 0};
202 /// splits "x=z, y=b" into a map
203 map<string, string> split_map(string const & s)
205 map<string, string> res;
208 for (size_t i = 0; i < v.size(); ++i) {
209 size_t const pos = v[i].find('=');
210 string const index = v[i].substr(0, pos);
211 string const value = v[i].substr(pos + 1, string::npos);
212 res[trim(index)] = trim(value);
219 * Split a LaTeX length into value and unit.
220 * The latter can be a real unit like "pt", or a latex length variable
221 * like "\textwidth". The unit may contain additional stuff like glue
222 * lengths, but we don't care, because such lengths are ERT anyway.
223 * \returns true if \p value and \p unit are valid.
225 bool splitLatexLength(string const & len, string & value, string & unit)
229 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
230 //'4,5' is a valid LaTeX length number. Change it to '4.5'
231 string const length = subst(len, ',', '.');
232 if (i == string::npos)
235 if (len[0] == '\\') {
236 // We had something like \textwidth without a factor
242 value = trim(string(length, 0, i));
246 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
247 if (contains(len, '\\'))
248 unit = trim(string(len, i));
250 unit = lyx::support::lowercase(trim(string(len, i)));
255 /// A simple function to translate a latex length to something lyx can
256 /// understand. Not perfect, but rather best-effort.
257 bool translate_len(string const & length, string & valstring, string & unit)
259 if (!splitLatexLength(length, valstring, unit))
261 // LyX uses percent values
263 istringstream iss(valstring);
268 string const percentval = oss.str();
270 if (unit.empty() || unit[0] != '\\')
272 string::size_type const i = unit.find(' ');
273 string const endlen = (i == string::npos) ? string() : string(unit, i);
274 if (unit == "\\textwidth") {
275 valstring = percentval;
276 unit = "text%" + endlen;
277 } else if (unit == "\\columnwidth") {
278 valstring = percentval;
279 unit = "col%" + endlen;
280 } else if (unit == "\\paperwidth") {
281 valstring = percentval;
282 unit = "page%" + endlen;
283 } else if (unit == "\\linewidth") {
284 valstring = percentval;
285 unit = "line%" + endlen;
286 } else if (unit == "\\paperheight") {
287 valstring = percentval;
288 unit = "pheight%" + endlen;
289 } else if (unit == "\\textheight") {
290 valstring = percentval;
291 unit = "theight%" + endlen;
297 string translate_len(string const & length)
301 if (translate_len(length, value, unit))
303 // If the input is invalid, return what we have.
309 * Translates a LaTeX length into \p value, \p unit and
310 * \p special parts suitable for a box inset.
311 * The difference from translate_len() is that a box inset knows about
312 * some special "units" that are stored in \p special.
314 void translate_box_len(string const & length, string & value, string & unit, string & special)
316 if (translate_len(length, value, unit)) {
317 if (unit == "\\height" || unit == "\\depth" ||
318 unit == "\\totalheight" || unit == "\\width") {
319 special = unit.substr(1);
320 // The unit is not used, but LyX requires a dummy setting
333 * Find a file with basename \p name in path \p path and an extension
336 string find_file(string const & name, string const & path,
337 char const * const * extensions)
339 for (char const * const * what = extensions; *what; ++what) {
340 // We don't use ChangeExtension() because it does the wrong
341 // thing if name contains a dot.
342 string const trial = name + '.' + (*what);
343 if (fs::exists(MakeAbsPath(trial, path)))
350 void begin_inset(ostream & os, string const & name)
352 os << "\n\\begin_inset " << name;
356 void end_inset(ostream & os)
358 os << "\n\\end_inset\n\n";
362 void skip_braces(Parser & p)
364 if (p.next_token().cat() != catBegin)
367 if (p.next_token().cat() == catEnd) {
375 void handle_ert(ostream & os, string const & s, Context & context)
377 // We must have a valid layout before outputting the ERT inset.
378 context.check_layout(os);
379 Context newcontext(true, context.textclass);
380 begin_inset(os, "ERT");
381 os << "\nstatus collapsed\n";
382 newcontext.check_layout(os);
383 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
385 os << "\n\\backslash\n";
386 else if (*it == '\n') {
387 newcontext.new_paragraph(os);
388 newcontext.check_layout(os);
392 newcontext.check_end_layout(os);
397 void handle_comment(ostream & os, string const & s, Context & context)
399 // TODO: Handle this better
400 Context newcontext(true, context.textclass);
401 begin_inset(os, "ERT");
402 os << "\nstatus collapsed\n";
403 newcontext.check_layout(os);
404 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
406 os << "\n\\backslash\n";
410 // make sure that our comment is the last thing on the line
411 newcontext.new_paragraph(os);
412 newcontext.check_layout(os);
413 newcontext.check_end_layout(os);
418 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
420 isLayout(string const name) : name_(name) {}
421 bool operator()(LyXLayout_ptr const & ptr) const {
422 return ptr->latexname() == name_;
429 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
432 LyXTextClass::const_iterator beg = textclass.begin();
433 LyXTextClass::const_iterator end = textclass.end();
435 LyXTextClass::const_iterator
436 it = std::find_if(beg, end, isLayout(name));
438 return (it == end) ? LyXLayout_ptr() : *it;
442 void eat_whitespace(Parser &, ostream &, Context &, bool);
445 void output_command_layout(ostream & os, Parser & p, bool outer,
446 Context & parent_context,
447 LyXLayout_ptr newlayout)
449 parent_context.check_end_layout(os);
450 Context context(true, parent_context.textclass, newlayout,
451 parent_context.layout, parent_context.font);
452 if (parent_context.deeper_paragraph) {
453 // We are beginning a nested environment after a
454 // deeper paragraph inside the outer list environment.
455 // Therefore we don't need to output a "begin deeper".
456 context.need_end_deeper = true;
458 context.check_deeper(os);
459 context.check_layout(os);
460 if (context.layout->optionalargs > 0) {
461 eat_whitespace(p, os, context, false);
462 if (p.next_token().character() == '[') {
463 p.get_token(); // eat '['
464 begin_inset(os, "OptArg\n");
465 os << "status collapsed\n\n";
466 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
468 eat_whitespace(p, os, context, false);
471 parse_text(p, os, FLAG_ITEM, outer, context);
472 context.check_end_layout(os);
473 if (parent_context.deeper_paragraph) {
474 // We must suppress the "end deeper" because we
475 // suppressed the "begin deeper" above.
476 context.need_end_deeper = false;
478 context.check_end_deeper(os);
479 // We don't need really a new paragraph, but
480 // we must make sure that the next item gets a \begin_layout.
481 parent_context.new_paragraph(os);
486 * Output a space if necessary.
487 * This function gets called for every whitespace token.
489 * We have three cases here:
490 * 1. A space must be suppressed. Example: The lyxcode case below
491 * 2. A space may be suppressed. Example: Spaces before "\par"
492 * 3. A space must not be suppressed. Example: A space between two words
494 * We currently handle only 1. and 3 and from 2. only the case of
495 * spaces before newlines as a side effect.
497 * 2. could be used to suppress as many spaces as possible. This has two effects:
498 * - Reimporting LyX generated LaTeX files changes almost no whitespace
499 * - Superflous whitespace from non LyX generated LaTeX files is removed.
500 * The drawback is that the logic inside the function becomes
501 * complicated, and that is the reason why it is not implemented.
503 void check_space(Parser const & p, ostream & os, Context & context)
505 Token const next = p.next_token();
506 Token const curr = p.curr_token();
507 // A space before a single newline and vice versa must be ignored
508 // LyX emits a newline before \end{lyxcode}.
509 // This newline must be ignored,
510 // otherwise LyX will add an additional protected space.
511 if (next.cat() == catSpace ||
512 next.cat() == catNewline ||
513 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
516 context.check_layout(os);
522 * Parse all arguments of \p command
524 void parse_arguments(string const & command,
525 vector<ArgumentType> const & template_arguments,
526 Parser & p, ostream & os, bool outer, Context & context)
528 string ert = command;
529 size_t no_arguments = template_arguments.size();
530 for (size_t i = 0; i < no_arguments; ++i) {
531 switch (template_arguments[i]) {
533 // This argument contains regular LaTeX
534 handle_ert(os, ert + '{', context);
535 parse_text(p, os, FLAG_ITEM, outer, context);
539 // This argument may contain special characters
540 ert += '{' + p.verbatim_item() + '}';
547 handle_ert(os, ert, context);
552 * Check whether \p command is a known command. If yes,
553 * handle the command with all arguments.
554 * \return true if the command was parsed, false otherwise.
556 bool parse_command(string const & command, Parser & p, ostream & os,
557 bool outer, Context & context)
559 if (known_commands.find(command) != known_commands.end()) {
560 parse_arguments(command, known_commands[command], p, os,
568 /// Parses a minipage or parbox
569 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
570 Context & parent_context, bool use_parbox)
574 string height_value = "0";
575 string height_unit = "pt";
576 string height_special = "none";
578 if (p.next_token().asInput() == "[") {
579 position = p.getArg('[', ']');
580 if (position != "t" && position != "c" && position != "b") {
582 cerr << "invalid position for minipage/parbox" << endl;
584 if (p.next_token().asInput() == "[") {
585 latex_height = p.getArg('[', ']');
586 translate_box_len(latex_height, height_value, height_unit, height_special);
588 if (p.next_token().asInput() == "[") {
589 inner_pos = p.getArg('[', ']');
590 if (inner_pos != "c" && inner_pos != "t" &&
591 inner_pos != "b" && inner_pos != "s") {
592 inner_pos = position;
593 cerr << "invalid inner_pos for minipage/parbox"
601 string const latex_width = p.verbatim_item();
602 translate_len(latex_width, width_value, width_unit);
603 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
604 // LyX can't handle length variables
609 ss << "\\begin{minipage}";
610 if (!position.empty())
611 ss << '[' << position << ']';
612 if (!latex_height.empty())
613 ss << '[' << latex_height << ']';
614 if (!inner_pos.empty())
615 ss << '[' << inner_pos << ']';
616 ss << "{" << latex_width << "}";
619 handle_ert(os, ss.str(), parent_context);
620 parent_context.new_paragraph(os);
621 parse_text_in_inset(p, os, flags, outer, parent_context);
623 handle_ert(os, "}", parent_context);
625 handle_ert(os, "\\end{minipage}", parent_context);
627 // LyX does not like empty positions, so we have
628 // to set them to the LaTeX default values here.
629 if (position.empty())
631 if (inner_pos.empty())
632 inner_pos = position;
633 parent_context.check_layout(os);
634 begin_inset(os, "Box Frameless\n");
635 os << "position \"" << position << "\"\n";
636 os << "hor_pos \"c\"\n";
637 os << "has_inner_box 1\n";
638 os << "inner_pos \"" << inner_pos << "\"\n";
639 os << "use_parbox " << use_parbox << "\n";
640 os << "width \"" << width_value << width_unit << "\"\n";
641 os << "special \"none\"\n";
642 os << "height \"" << height_value << height_unit << "\"\n";
643 os << "height_special \"" << height_special << "\"\n";
644 os << "status open\n\n";
645 parse_text_in_inset(p, os, flags, outer, parent_context);
647 #ifdef PRESERVE_LAYOUT
648 // lyx puts a % after the end of the minipage
649 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
651 //handle_comment(os, "%dummy", parent_context);
654 parent_context.new_paragraph(os);
656 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
657 //handle_comment(os, "%dummy", parent_context);
660 // We add a protected space if something real follows
661 if (p.good() && p.next_token().cat() != catComment) {
662 os << "\\InsetSpace ~\n";
670 /// parse an unknown environment
671 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
672 unsigned flags, bool outer,
673 Context & parent_context)
675 if (name == "tabbing")
676 // We need to remember that we have to handle '\=' specially
677 flags |= FLAG_TABBING;
679 // We need to translate font changes and paragraphs inside the
680 // environment to ERT if we have a non standard font.
681 // Otherwise things like
682 // \large\begin{foo}\huge bar\end{foo}
684 bool const specialfont =
685 (parent_context.font != parent_context.normalfont);
686 bool const new_layout_allowed = parent_context.new_layout_allowed;
688 parent_context.new_layout_allowed = false;
689 handle_ert(os, "\\begin{" + name + "}", parent_context);
690 parse_text_snippet(p, os, flags, outer, parent_context);
691 handle_ert(os, "\\end{" + name + "}", parent_context);
693 parent_context.new_layout_allowed = new_layout_allowed;
697 void parse_environment(Parser & p, ostream & os, bool outer,
698 Context & parent_context)
700 LyXLayout_ptr newlayout;
701 string const name = p.getArg('{', '}');
702 const bool is_starred = suffixIs(name, '*');
703 string const unstarred_name = rtrim(name, "*");
704 active_environments.push_back(name);
706 if (is_math_env(name)) {
707 parent_context.check_layout(os);
708 begin_inset(os, "Formula ");
709 os << "\\begin{" << name << "}";
710 parse_math(p, os, FLAG_END, MATH_MODE);
711 os << "\\end{" << name << "}";
715 else if (name == "tabular" || name == "longtable") {
716 eat_whitespace(p, os, parent_context, false);
717 parent_context.check_layout(os);
718 begin_inset(os, "Tabular ");
719 handle_tabular(p, os, name == "longtable", parent_context);
724 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
725 eat_whitespace(p, os, parent_context, false);
726 parent_context.check_layout(os);
727 begin_inset(os, "Float " + unstarred_name + "\n");
728 if (p.next_token().asInput() == "[") {
729 os << "placement " << p.getArg('[', ']') << '\n';
731 os << "wide " << convert<string>(is_starred)
732 << "\nsideways false"
733 << "\nstatus open\n\n";
734 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
736 // We don't need really a new paragraph, but
737 // we must make sure that the next item gets a \begin_layout.
738 parent_context.new_paragraph(os);
742 else if (name == "minipage") {
743 eat_whitespace(p, os, parent_context, false);
744 parse_box(p, os, FLAG_END, outer, parent_context, false);
748 else if (name == "comment") {
749 eat_whitespace(p, os, parent_context, false);
750 parent_context.check_layout(os);
751 begin_inset(os, "Note Comment\n");
752 os << "status open\n";
753 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
758 else if (name == "lyxgreyedout") {
759 eat_whitespace(p, os, parent_context, false);
760 parent_context.check_layout(os);
761 begin_inset(os, "Note Greyedout\n");
762 os << "status open\n";
763 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
768 else if (!parent_context.new_layout_allowed)
769 parse_unknown_environment(p, name, os, FLAG_END, outer,
772 // Alignment settings
773 else if (name == "center" || name == "flushleft" || name == "flushright" ||
774 name == "centering" || name == "raggedright" || name == "raggedleft") {
775 eat_whitespace(p, os, parent_context, false);
776 // We must begin a new paragraph if not already done
777 if (! parent_context.atParagraphStart()) {
778 parent_context.check_end_layout(os);
779 parent_context.new_paragraph(os);
781 if (name == "flushleft" || name == "raggedright")
782 parent_context.add_extra_stuff("\\align left\n");
783 else if (name == "flushright" || name == "raggedleft")
784 parent_context.add_extra_stuff("\\align right\n");
786 parent_context.add_extra_stuff("\\align center\n");
787 parse_text(p, os, FLAG_END, outer, parent_context);
788 // Just in case the environment is empty ..
789 parent_context.extra_stuff.erase();
790 // We must begin a new paragraph to reset the alignment
791 parent_context.new_paragraph(os);
795 // The single '=' is meant here.
796 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
797 newlayout->isEnvironment()) {
798 eat_whitespace(p, os, parent_context, false);
799 Context context(true, parent_context.textclass, newlayout,
800 parent_context.layout, parent_context.font);
801 if (parent_context.deeper_paragraph) {
802 // We are beginning a nested environment after a
803 // deeper paragraph inside the outer list environment.
804 // Therefore we don't need to output a "begin deeper".
805 context.need_end_deeper = true;
807 parent_context.check_end_layout(os);
808 switch (context.layout->latextype) {
809 case LATEX_LIST_ENVIRONMENT:
810 context.extra_stuff = "\\labelwidthstring "
811 + p.verbatim_item() + '\n';
814 case LATEX_BIB_ENVIRONMENT:
815 p.verbatim_item(); // swallow next arg
821 context.check_deeper(os);
822 parse_text(p, os, FLAG_END, outer, context);
823 context.check_end_layout(os);
824 if (parent_context.deeper_paragraph) {
825 // We must suppress the "end deeper" because we
826 // suppressed the "begin deeper" above.
827 context.need_end_deeper = false;
829 context.check_end_deeper(os);
830 parent_context.new_paragraph(os);
834 else if (name == "appendix") {
835 // This is no good latex style, but it works and is used in some documents...
836 eat_whitespace(p, os, parent_context, false);
837 parent_context.check_end_layout(os);
838 Context context(true, parent_context.textclass, parent_context.layout,
839 parent_context.layout, parent_context.font);
840 context.check_layout(os);
841 os << "\\start_of_appendix\n";
842 parse_text(p, os, FLAG_END, outer, context);
843 context.check_end_layout(os);
847 else if (known_environments.find(name) != known_environments.end()) {
848 vector<ArgumentType> arguments = known_environments[name];
849 // The last "argument" denotes wether we may translate the
850 // environment contents to LyX
851 // The default required if no argument is given makes us
852 // compatible with the reLyXre environment.
853 ArgumentType contents = arguments.empty() ?
856 if (!arguments.empty())
857 arguments.pop_back();
858 // See comment in parse_unknown_environment()
859 bool const specialfont =
860 (parent_context.font != parent_context.normalfont);
861 bool const new_layout_allowed =
862 parent_context.new_layout_allowed;
864 parent_context.new_layout_allowed = false;
865 parse_arguments("\\begin{" + name + "}", arguments, p, os,
866 outer, parent_context);
867 if (contents == verbatim)
868 handle_ert(os, p.verbatimEnvironment(name),
871 parse_text_snippet(p, os, FLAG_END, outer,
873 handle_ert(os, "\\end{" + name + "}", parent_context);
875 parent_context.new_layout_allowed = new_layout_allowed;
879 parse_unknown_environment(p, name, os, FLAG_END, outer,
882 active_environments.pop_back();
886 /// parses a comment and outputs it to \p os.
887 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
889 BOOST_ASSERT(t.cat() == catComment);
890 if (!t.cs().empty()) {
891 context.check_layout(os);
892 handle_comment(os, '%' + t.cs(), context);
893 if (p.next_token().cat() == catNewline) {
894 // A newline after a comment line starts a new
896 if (context.new_layout_allowed) {
897 if(!context.atParagraphStart())
898 // Only start a new paragraph if not already
899 // done (we might get called recursively)
900 context.new_paragraph(os);
902 handle_ert(os, "\n", context);
903 eat_whitespace(p, os, context, true);
913 * Reads spaces and comments until the first non-space, non-comment token.
914 * New paragraphs (double newlines or \\par) are handled like simple spaces
915 * if \p eatParagraph is true.
916 * Spaces are skipped, but comments are written to \p os.
918 void eat_whitespace(Parser & p, ostream & os, Context & context,
922 Token const & t = p.get_token();
923 if (t.cat() == catComment)
924 parse_comment(p, os, t, context);
925 else if ((! eatParagraph && p.isParagraph()) ||
926 (t.cat() != catSpace && t.cat() != catNewline)) {
935 * Set a font attribute, parse text and reset the font attribute.
936 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
937 * \param currentvalue Current value of the attribute. Is set to the new
938 * value during parsing.
939 * \param newvalue New value of the attribute
941 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
942 Context & context, string const & attribute,
943 string & currentvalue, string const & newvalue)
945 context.check_layout(os);
946 string const oldvalue = currentvalue;
947 currentvalue = newvalue;
948 os << '\n' << attribute << ' ' << newvalue << "\n";
949 parse_text_snippet(p, os, flags, outer, context);
950 context.check_layout(os);
951 os << '\n' << attribute << ' ' << oldvalue << "\n";
952 currentvalue = oldvalue;
956 /// get the arguments of a natbib or jurabib citation command
957 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
959 // We need to distinguish "" and "[]", so we can't use p.getOpt().
961 // text before the citation
963 // text after the citation
964 string after = p.getFullOpt();
966 if (!after.empty()) {
967 before = p.getFullOpt();
968 if (natbibOrder && !before.empty())
969 std::swap(before, after);
971 return std::make_pair(before, after);
975 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
976 string const normalize_filename(string const & name)
978 Parser p(trim(name, "\""));
981 Token const & t = p.get_token();
982 if (t.cat() != catEscape)
984 else if (t.cs() == "lyxdot") {
985 // This is used by LyX for simple dots in relative
989 } else if (t.cs() == "space") {
999 /// Convert \p name from TeX convention (relative to master file) to LyX
1000 /// convention (relative to .lyx file) if it is relative
1001 void fix_relative_filename(string & name)
1003 if (lyx::support::AbsolutePath(name))
1005 name = MakeRelPath(MakeAbsPath(name, getMasterFilePath()),
1006 getParentFilePath());
1009 } // anonymous namespace
1012 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1015 LyXLayout_ptr newlayout;
1016 // Store the latest bibliographystyle (needed for bibtex inset)
1017 string bibliographystyle;
1018 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1019 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1021 Token const & t = p.get_token();
1024 cerr << "t: " << t << " flags: " << flags << "\n";
1027 if (flags & FLAG_ITEM) {
1028 if (t.cat() == catSpace)
1031 flags &= ~FLAG_ITEM;
1032 if (t.cat() == catBegin) {
1033 // skip the brace and collect everything to the next matching
1035 flags |= FLAG_BRACE_LAST;
1039 // handle only this single token, leave the loop if done
1040 flags |= FLAG_LEAVE;
1043 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1049 if (t.cat() == catMath) {
1050 // we are inside some text mode thingy, so opening new math is allowed
1051 context.check_layout(os);
1052 begin_inset(os, "Formula ");
1053 Token const & n = p.get_token();
1054 if (n.cat() == catMath && outer) {
1055 // TeX's $$...$$ syntax for displayed math
1057 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1059 p.get_token(); // skip the second '$' token
1061 // simple $...$ stuff
1064 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1070 else if (t.cat() == catSuper || t.cat() == catSub)
1071 cerr << "catcode " << t << " illegal in text mode\n";
1073 // Basic support for english quotes. This should be
1074 // extended to other quotes, but is not so easy (a
1075 // left english quote is the same as a right german
1077 else if (t.asInput() == "`"
1078 && p.next_token().asInput() == "`") {
1079 context.check_layout(os);
1080 begin_inset(os, "Quotes ");
1086 else if (t.asInput() == "'"
1087 && p.next_token().asInput() == "'") {
1088 context.check_layout(os);
1089 begin_inset(os, "Quotes ");
1096 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1097 check_space(p, os, context);
1099 else if (t.cat() == catLetter ||
1100 t.cat() == catOther ||
1101 t.cat() == catAlign ||
1102 t.cat() == catParameter) {
1103 // This translates "&" to "\\&" which may be wrong...
1104 context.check_layout(os);
1105 os << t.character();
1108 else if (p.isParagraph()) {
1109 if (context.new_layout_allowed)
1110 context.new_paragraph(os);
1112 handle_ert(os, "\\par ", context);
1113 eat_whitespace(p, os, context, true);
1116 else if (t.cat() == catActive) {
1117 context.check_layout(os);
1118 if (t.character() == '~') {
1119 if (context.layout->free_spacing)
1122 os << "\\InsetSpace ~\n";
1124 os << t.character();
1127 else if (t.cat() == catBegin &&
1128 p.next_token().cat() == catEnd) {
1130 Token const prev = p.prev_token();
1132 if (p.next_token().character() == '`' ||
1133 (prev.character() == '-' &&
1134 p.next_token().character() == '-'))
1135 ; // ignore it in {}`` or -{}-
1137 handle_ert(os, "{}", context);
1141 else if (t.cat() == catBegin) {
1142 context.check_layout(os);
1143 // special handling of font attribute changes
1144 Token const prev = p.prev_token();
1145 Token const next = p.next_token();
1146 Font const oldFont = context.font;
1147 if (next.character() == '[' ||
1148 next.character() == ']' ||
1149 next.character() == '*') {
1151 if (p.next_token().cat() == catEnd) {
1152 os << next.character();
1156 handle_ert(os, "{", context);
1157 parse_text_snippet(p, os,
1160 handle_ert(os, "}", context);
1162 } else if (! context.new_layout_allowed) {
1163 handle_ert(os, "{", context);
1164 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1166 handle_ert(os, "}", context);
1167 } else if (is_known(next.cs(), known_sizes)) {
1168 // next will change the size, so we must
1170 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1172 if (!context.atParagraphStart())
1174 << context.font.size << "\n";
1175 } else if (is_known(next.cs(), known_font_families)) {
1176 // next will change the font family, so we
1177 // must reset it here
1178 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1180 if (!context.atParagraphStart())
1182 << context.font.family << "\n";
1183 } else if (is_known(next.cs(), known_font_series)) {
1184 // next will change the font series, so we
1185 // must reset it here
1186 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1188 if (!context.atParagraphStart())
1190 << context.font.series << "\n";
1191 } else if (is_known(next.cs(), known_font_shapes)) {
1192 // next will change the font shape, so we
1193 // must reset it here
1194 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1196 if (!context.atParagraphStart())
1198 << context.font.shape << "\n";
1199 } else if (is_known(next.cs(), known_old_font_families) ||
1200 is_known(next.cs(), known_old_font_series) ||
1201 is_known(next.cs(), known_old_font_shapes)) {
1202 // next will change the font family, series
1203 // and shape, so we must reset it here
1204 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1206 if (!context.atParagraphStart())
1208 << context.font.family
1210 << context.font.series
1212 << context.font.shape << "\n";
1214 handle_ert(os, "{", context);
1215 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1217 handle_ert(os, "}", context);
1221 else if (t.cat() == catEnd) {
1222 if (flags & FLAG_BRACE_LAST) {
1225 cerr << "stray '}' in text\n";
1226 handle_ert(os, "}", context);
1229 else if (t.cat() == catComment)
1230 parse_comment(p, os, t, context);
1233 // control sequences
1236 else if (t.cs() == "(") {
1237 context.check_layout(os);
1238 begin_inset(os, "Formula");
1240 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1245 else if (t.cs() == "[") {
1246 context.check_layout(os);
1247 begin_inset(os, "Formula");
1249 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1254 else if (t.cs() == "begin")
1255 parse_environment(p, os, outer, context);
1257 else if (t.cs() == "end") {
1258 if (flags & FLAG_END) {
1259 // eat environment name
1260 string const name = p.getArg('{', '}');
1261 if (name != active_environment())
1262 cerr << "\\end{" + name + "} does not match \\begin{"
1263 + active_environment() + "}\n";
1266 p.error("found 'end' unexpectedly");
1269 else if (t.cs() == "item") {
1272 bool optarg = false;
1273 if (p.next_token().character() == '[') {
1274 p.get_token(); // eat '['
1275 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1280 context.check_layout(os);
1282 if (context.layout->labeltype != LABEL_MANUAL) {
1283 // lyx does not support \item[\mybullet]
1284 // in itemize environments
1285 handle_ert(os, "[", context);
1287 handle_ert(os, "]", context);
1288 } else if (!s.empty()) {
1289 // The space is needed to separate the
1290 // item from the rest of the sentence.
1292 eat_whitespace(p, os, context, false);
1297 else if (t.cs() == "bibitem") {
1299 context.check_layout(os);
1302 os << '{' << p.verbatim_item() << '}' << "\n";
1305 else if (t.cs() == "def") {
1306 context.check_layout(os);
1307 eat_whitespace(p, os, context, false);
1308 string name = p.get_token().cs();
1309 while (p.next_token().cat() != catBegin)
1310 name += p.get_token().asString();
1311 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1314 else if (t.cs() == "noindent") {
1316 context.add_extra_stuff("\\noindent\n");
1319 else if (t.cs() == "appendix") {
1320 context.add_extra_stuff("\\start_of_appendix\n");
1321 // We need to start a new paragraph. Otherwise the
1322 // appendix in 'bla\appendix\chapter{' would start
1324 context.new_paragraph(os);
1325 // We need to make sure that the paragraph is
1326 // generated even if it is empty. Otherwise the
1327 // appendix in '\par\appendix\par\chapter{' would
1329 context.check_layout(os);
1330 // FIXME: This is a hack to prevent paragraph
1331 // deletion if it is empty. Handle this better!
1333 "%dummy comment inserted by tex2lyx to "
1334 "ensure that this paragraph is not empty",
1336 // Both measures above may generate an additional
1337 // empty paragraph, but that does not hurt, because
1338 // whitespace does not matter here.
1339 eat_whitespace(p, os, context, true);
1342 // Must attempt to parse "Section*" before "Section".
1343 else if ((p.next_token().asInput() == "*") &&
1344 context.new_layout_allowed &&
1345 // The single '=' is meant here.
1346 (newlayout = findLayout(context.textclass,
1347 t.cs() + '*')).get() &&
1348 newlayout->isCommand()) {
1350 output_command_layout(os, p, outer, context, newlayout);
1354 // The single '=' is meant here.
1355 else if (context.new_layout_allowed &&
1356 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1357 newlayout->isCommand()) {
1358 output_command_layout(os, p, outer, context, newlayout);
1362 else if (t.cs() == "includegraphics") {
1363 bool const clip = p.next_token().asInput() == "*";
1366 map<string, string> opts = split_map(p.getArg('[', ']'));
1368 opts["clip"] = string();
1369 string name = normalize_filename(p.verbatim_item());
1371 string const path = getMasterFilePath();
1372 // We want to preserve relative / absolute filenames,
1373 // therefore path is only used for testing
1374 if (!fs::exists(MakeAbsPath(name, path))) {
1375 // The file extension is probably missing.
1376 // Now try to find it out.
1377 string const dvips_name =
1378 find_file(name, path,
1379 known_dvips_graphics_formats);
1380 string const pdftex_name =
1381 find_file(name, path,
1382 known_pdftex_graphics_formats);
1383 if (!dvips_name.empty()) {
1384 if (!pdftex_name.empty()) {
1385 cerr << "This file contains the "
1387 "\"\\includegraphics{"
1389 "However, files\n\""
1390 << dvips_name << "\" and\n\""
1391 << pdftex_name << "\"\n"
1392 "both exist, so I had to make a "
1393 "choice and took the first one.\n"
1394 "Please move the unwanted one "
1395 "someplace else and try again\n"
1396 "if my choice was wrong."
1400 } else if (!pdftex_name.empty())
1404 if (fs::exists(MakeAbsPath(name, path)))
1405 fix_relative_filename(name);
1407 cerr << "Warning: Could not find graphics file '"
1408 << name << "'." << endl;
1410 context.check_layout(os);
1411 begin_inset(os, "Graphics ");
1412 os << "\n\tfilename " << name << '\n';
1413 if (opts.find("width") != opts.end())
1415 << translate_len(opts["width"]) << '\n';
1416 if (opts.find("height") != opts.end())
1418 << translate_len(opts["height"]) << '\n';
1419 if (opts.find("scale") != opts.end()) {
1420 istringstream iss(opts["scale"]);
1424 os << "\tscale " << val << '\n';
1426 if (opts.find("angle") != opts.end())
1427 os << "\trotateAngle "
1428 << opts["angle"] << '\n';
1429 if (opts.find("origin") != opts.end()) {
1431 string const opt = opts["origin"];
1432 if (opt.find('l') != string::npos) ss << "left";
1433 if (opt.find('r') != string::npos) ss << "right";
1434 if (opt.find('c') != string::npos) ss << "center";
1435 if (opt.find('t') != string::npos) ss << "Top";
1436 if (opt.find('b') != string::npos) ss << "Bottom";
1437 if (opt.find('B') != string::npos) ss << "Baseline";
1438 if (!ss.str().empty())
1439 os << "\trotateOrigin " << ss.str() << '\n';
1441 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1443 if (opts.find("keepaspectratio") != opts.end())
1444 os << "\tkeepAspectRatio\n";
1445 if (opts.find("clip") != opts.end())
1447 if (opts.find("draft") != opts.end())
1449 if (opts.find("bb") != opts.end())
1450 os << "\tBoundingBox "
1451 << opts["bb"] << '\n';
1452 int numberOfbbOptions = 0;
1453 if (opts.find("bbllx") != opts.end())
1454 numberOfbbOptions++;
1455 if (opts.find("bblly") != opts.end())
1456 numberOfbbOptions++;
1457 if (opts.find("bburx") != opts.end())
1458 numberOfbbOptions++;
1459 if (opts.find("bbury") != opts.end())
1460 numberOfbbOptions++;
1461 if (numberOfbbOptions == 4)
1462 os << "\tBoundingBox "
1463 << opts["bbllx"] << opts["bblly"]
1464 << opts["bburx"] << opts["bbury"] << '\n';
1465 else if (numberOfbbOptions > 0)
1466 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1467 numberOfbbOptions = 0;
1468 if (opts.find("natwidth") != opts.end())
1469 numberOfbbOptions++;
1470 if (opts.find("natheight") != opts.end())
1471 numberOfbbOptions++;
1472 if (numberOfbbOptions == 2)
1473 os << "\tBoundingBox 0bp 0bp "
1474 << opts["natwidth"] << opts["natheight"] << '\n';
1475 else if (numberOfbbOptions > 0)
1476 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1477 ostringstream special;
1478 if (opts.find("hiresbb") != opts.end())
1479 special << "hiresbb,";
1480 if (opts.find("trim") != opts.end())
1482 if (opts.find("viewport") != opts.end())
1483 special << "viewport=" << opts["viewport"] << ',';
1484 if (opts.find("totalheight") != opts.end())
1485 special << "totalheight=" << opts["totalheight"] << ',';
1486 if (opts.find("type") != opts.end())
1487 special << "type=" << opts["type"] << ',';
1488 if (opts.find("ext") != opts.end())
1489 special << "ext=" << opts["ext"] << ',';
1490 if (opts.find("read") != opts.end())
1491 special << "read=" << opts["read"] << ',';
1492 if (opts.find("command") != opts.end())
1493 special << "command=" << opts["command"] << ',';
1494 string s_special = special.str();
1495 if (!s_special.empty()) {
1496 // We had special arguments. Remove the trailing ','.
1497 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1499 // TODO: Handle the unknown settings better.
1500 // Warn about invalid options.
1501 // Check whether some option was given twice.
1505 else if (t.cs() == "footnote" ||
1506 (t.cs() == "thanks" && context.layout->intitle)) {
1508 context.check_layout(os);
1509 begin_inset(os, "Foot\n");
1510 os << "status collapsed\n\n";
1511 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1515 else if (t.cs() == "marginpar") {
1517 context.check_layout(os);
1518 begin_inset(os, "Marginal\n");
1519 os << "status collapsed\n\n";
1520 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1524 else if (t.cs() == "ensuremath") {
1526 context.check_layout(os);
1527 string const s = p.verbatim_item();
1528 if (s == "±" || s == "³" || s == "²" || s == "µ")
1531 handle_ert(os, "\\ensuremath{" + s + "}",
1535 else if (t.cs() == "hfill") {
1536 context.check_layout(os);
1537 os << "\n\\hfill\n";
1542 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1543 // FIXME: Somehow prevent title layouts if
1544 // "maketitle" was not found
1546 skip_braces(p); // swallow this
1549 else if (t.cs() == "tableofcontents") {
1551 context.check_layout(os);
1552 begin_inset(os, "LatexCommand \\tableofcontents\n");
1554 skip_braces(p); // swallow this
1557 else if (t.cs() == "listoffigures") {
1559 context.check_layout(os);
1560 begin_inset(os, "FloatList figure\n");
1562 skip_braces(p); // swallow this
1565 else if (t.cs() == "listoftables") {
1567 context.check_layout(os);
1568 begin_inset(os, "FloatList table\n");
1570 skip_braces(p); // swallow this
1573 else if (t.cs() == "listof") {
1574 p.skip_spaces(true);
1575 string const name = p.get_token().asString();
1576 if (context.textclass.floats().typeExist(name)) {
1577 context.check_layout(os);
1578 begin_inset(os, "FloatList ");
1581 p.get_token(); // swallow second arg
1583 handle_ert(os, "\\listof{" + name + "}", context);
1586 else if (t.cs() == "textrm")
1587 parse_text_attributes(p, os, FLAG_ITEM, outer,
1588 context, "\\family",
1589 context.font.family, "roman");
1591 else if (t.cs() == "textsf")
1592 parse_text_attributes(p, os, FLAG_ITEM, outer,
1593 context, "\\family",
1594 context.font.family, "sans");
1596 else if (t.cs() == "texttt")
1597 parse_text_attributes(p, os, FLAG_ITEM, outer,
1598 context, "\\family",
1599 context.font.family, "typewriter");
1601 else if (t.cs() == "textmd")
1602 parse_text_attributes(p, os, FLAG_ITEM, outer,
1603 context, "\\series",
1604 context.font.series, "medium");
1606 else if (t.cs() == "textbf")
1607 parse_text_attributes(p, os, FLAG_ITEM, outer,
1608 context, "\\series",
1609 context.font.series, "bold");
1611 else if (t.cs() == "textup")
1612 parse_text_attributes(p, os, FLAG_ITEM, outer,
1614 context.font.shape, "up");
1616 else if (t.cs() == "textit")
1617 parse_text_attributes(p, os, FLAG_ITEM, outer,
1619 context.font.shape, "italic");
1621 else if (t.cs() == "textsl")
1622 parse_text_attributes(p, os, FLAG_ITEM, outer,
1624 context.font.shape, "slanted");
1626 else if (t.cs() == "textsc")
1627 parse_text_attributes(p, os, FLAG_ITEM, outer,
1629 context.font.shape, "smallcaps");
1631 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1632 context.check_layout(os);
1633 Font oldFont = context.font;
1634 context.font.init();
1635 context.font.size = oldFont.size;
1636 os << "\n\\family " << context.font.family << "\n";
1637 os << "\n\\series " << context.font.series << "\n";
1638 os << "\n\\shape " << context.font.shape << "\n";
1639 if (t.cs() == "textnormal") {
1640 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1641 output_font_change(os, context.font, oldFont);
1642 context.font = oldFont;
1644 eat_whitespace(p, os, context, false);
1647 else if (t.cs() == "underbar") {
1648 // Do NOT handle \underline.
1649 // \underbar cuts through y, g, q, p etc.,
1650 // \underline does not.
1651 context.check_layout(os);
1652 os << "\n\\bar under\n";
1653 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1654 context.check_layout(os);
1655 os << "\n\\bar default\n";
1658 else if (t.cs() == "emph" || t.cs() == "noun") {
1659 context.check_layout(os);
1660 os << "\n\\" << t.cs() << " on\n";
1661 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1662 context.check_layout(os);
1663 os << "\n\\" << t.cs() << " default\n";
1666 else if (use_natbib &&
1667 is_known(t.cs(), known_natbib_commands) &&
1668 ((t.cs() != "citefullauthor" &&
1669 t.cs() != "citeyear" &&
1670 t.cs() != "citeyearpar") ||
1671 p.next_token().asInput() != "*")) {
1672 context.check_layout(os);
1674 // \citet[before][after]{a} \citet[after][before]{a}
1675 // \citet[before][]{a} \citet[][before]{a}
1676 // \citet[after]{a} \citet[after]{a}
1677 // \citet{a} \citet{a}
1678 string command = '\\' + t.cs();
1679 if (p.next_token().asInput() == "*") {
1683 if (command == "\\citefullauthor")
1684 // alternative name for "\\citeauthor*"
1685 command = "\\citeauthor*";
1687 // text before the citation
1689 // text after the citation
1692 boost::tie(before, after) = getCiteArguments(p, true);
1693 if (command == "\\cite") {
1694 // \cite without optional argument means
1695 // \citet, \cite with at least one optional
1696 // argument means \citep.
1697 if (before.empty() && after.empty())
1698 command = "\\citet";
1700 command = "\\citep";
1702 if (before.empty() && after == "[]")
1703 // avoid \citet[]{a}
1705 else if (before == "[]" && after == "[]") {
1706 // avoid \citet[][]{a}
1710 begin_inset(os, "LatexCommand ");
1711 os << command << after << before
1712 << '{' << p.verbatim_item() << "}\n";
1716 else if (use_jurabib &&
1717 is_known(t.cs(), known_jurabib_commands)) {
1718 context.check_layout(os);
1719 string const command = '\\' + t.cs();
1720 char argumentOrder = '\0';
1721 vector<string> const & options = used_packages["jurabib"];
1722 if (std::find(options.begin(), options.end(),
1723 "natbiborder") != options.end())
1724 argumentOrder = 'n';
1725 else if (std::find(options.begin(), options.end(),
1726 "jurabiborder") != options.end())
1727 argumentOrder = 'j';
1729 // text before the citation
1731 // text after the citation
1734 boost::tie(before, after) =
1735 getCiteArguments(p, argumentOrder != 'j');
1736 string const citation = p.verbatim_item();
1737 if (!before.empty() && argumentOrder == '\0') {
1738 cerr << "Warning: Assuming argument order "
1739 "of jurabib version 0.6 for\n'"
1740 << command << before << after << '{'
1741 << citation << "}'.\n"
1742 "Add 'jurabiborder' to the jurabib "
1743 "package options if you used an\n"
1744 "earlier jurabib version." << endl;
1746 begin_inset(os, "LatexCommand ");
1747 os << command << after << before
1748 << '{' << citation << "}\n";
1752 else if (is_known(t.cs(), known_latex_commands)) {
1753 // This needs to be after the check for natbib and
1754 // jurabib commands, because "cite" has different
1755 // arguments with natbib and jurabib.
1756 context.check_layout(os);
1757 begin_inset(os, "LatexCommand ");
1758 os << '\\' << t.cs();
1759 // lyx cannot handle newlines in a latex command
1760 // FIXME: Move the substitution into parser::getOpt()?
1761 os << subst(p.getOpt(), "\n", " ");
1762 os << subst(p.getOpt(), "\n", " ");
1763 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1767 else if (is_known(t.cs(), known_quotes)) {
1768 char const * const * where = is_known(t.cs(), known_quotes);
1769 context.check_layout(os);
1770 begin_inset(os, "Quotes ");
1771 os << known_coded_quotes[where - known_quotes];
1773 // LyX adds {} after the quote, so we have to eat
1774 // spaces here if there are any before a possible
1776 eat_whitespace(p, os, context, false);
1780 else if (is_known(t.cs(), known_sizes) &&
1781 context.new_layout_allowed) {
1782 char const * const * where = is_known(t.cs(), known_sizes);
1783 context.check_layout(os);
1784 Font const oldFont = context.font;
1785 context.font.size = known_coded_sizes[where - known_sizes];
1786 output_font_change(os, oldFont, context.font);
1787 eat_whitespace(p, os, context, false);
1790 else if (is_known(t.cs(), known_font_families) &&
1791 context.new_layout_allowed) {
1792 char const * const * where =
1793 is_known(t.cs(), known_font_families);
1794 context.check_layout(os);
1795 Font const oldFont = context.font;
1796 context.font.family =
1797 known_coded_font_families[where - known_font_families];
1798 output_font_change(os, oldFont, context.font);
1799 eat_whitespace(p, os, context, false);
1802 else if (is_known(t.cs(), known_font_series) &&
1803 context.new_layout_allowed) {
1804 char const * const * where =
1805 is_known(t.cs(), known_font_series);
1806 context.check_layout(os);
1807 Font const oldFont = context.font;
1808 context.font.series =
1809 known_coded_font_series[where - known_font_series];
1810 output_font_change(os, oldFont, context.font);
1811 eat_whitespace(p, os, context, false);
1814 else if (is_known(t.cs(), known_font_shapes) &&
1815 context.new_layout_allowed) {
1816 char const * const * where =
1817 is_known(t.cs(), known_font_shapes);
1818 context.check_layout(os);
1819 Font const oldFont = context.font;
1820 context.font.shape =
1821 known_coded_font_shapes[where - known_font_shapes];
1822 output_font_change(os, oldFont, context.font);
1823 eat_whitespace(p, os, context, false);
1825 else if (is_known(t.cs(), known_old_font_families) &&
1826 context.new_layout_allowed) {
1827 char const * const * where =
1828 is_known(t.cs(), known_old_font_families);
1829 context.check_layout(os);
1830 Font const oldFont = context.font;
1831 context.font.init();
1832 context.font.size = oldFont.size;
1833 context.font.family =
1834 known_coded_font_families[where - known_old_font_families];
1835 output_font_change(os, oldFont, context.font);
1836 eat_whitespace(p, os, context, false);
1839 else if (is_known(t.cs(), known_old_font_series) &&
1840 context.new_layout_allowed) {
1841 char const * const * where =
1842 is_known(t.cs(), known_old_font_series);
1843 context.check_layout(os);
1844 Font const oldFont = context.font;
1845 context.font.init();
1846 context.font.size = oldFont.size;
1847 context.font.series =
1848 known_coded_font_series[where - known_old_font_series];
1849 output_font_change(os, oldFont, context.font);
1850 eat_whitespace(p, os, context, false);
1853 else if (is_known(t.cs(), known_old_font_shapes) &&
1854 context.new_layout_allowed) {
1855 char const * const * where =
1856 is_known(t.cs(), known_old_font_shapes);
1857 context.check_layout(os);
1858 Font const oldFont = context.font;
1859 context.font.init();
1860 context.font.size = oldFont.size;
1861 context.font.shape =
1862 known_coded_font_shapes[where - known_old_font_shapes];
1863 output_font_change(os, oldFont, context.font);
1864 eat_whitespace(p, os, context, false);
1867 else if (t.cs() == "LyX" || t.cs() == "TeX"
1868 || t.cs() == "LaTeX") {
1869 context.check_layout(os);
1871 skip_braces(p); // eat {}
1874 else if (t.cs() == "LaTeXe") {
1875 context.check_layout(os);
1877 skip_braces(p); // eat {}
1880 else if (t.cs() == "ldots") {
1881 context.check_layout(os);
1883 os << "\\SpecialChar \\ldots{}\n";
1886 else if (t.cs() == "lyxarrow") {
1887 context.check_layout(os);
1888 os << "\\SpecialChar \\menuseparator\n";
1892 else if (t.cs() == "textcompwordmark") {
1893 context.check_layout(os);
1894 os << "\\SpecialChar \\textcompwordmark{}\n";
1898 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1899 context.check_layout(os);
1900 os << "\\SpecialChar \\@.\n";
1904 else if (t.cs() == "-") {
1905 context.check_layout(os);
1906 os << "\\SpecialChar \\-\n";
1909 else if (t.cs() == "textasciitilde") {
1910 context.check_layout(os);
1915 else if (t.cs() == "textasciicircum") {
1916 context.check_layout(os);
1921 else if (t.cs() == "textbackslash") {
1922 context.check_layout(os);
1923 os << "\n\\backslash\n";
1927 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1928 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1930 context.check_layout(os);
1934 else if (t.cs() == "char") {
1935 context.check_layout(os);
1936 if (p.next_token().character() == '`') {
1938 if (p.next_token().cs() == "\"") {
1943 handle_ert(os, "\\char`", context);
1946 handle_ert(os, "\\char", context);
1950 else if (t.cs() == "\"") {
1951 context.check_layout(os);
1952 string const name = p.verbatim_item();
1953 if (name == "a") os << 'ä';
1954 else if (name == "o") os << 'ö';
1955 else if (name == "u") os << 'ü';
1956 else if (name == "A") os << 'Ä';
1957 else if (name == "O") os << 'Ö';
1958 else if (name == "U") os << 'Ü';
1959 else handle_ert(os, "\"{" + name + "}", context);
1962 // Problem: \= creates a tabstop inside the tabbing environment
1963 // and else an accent. In the latter case we really would want
1964 // \={o} instead of \= o.
1965 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1966 handle_ert(os, t.asInput(), context);
1968 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1969 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1970 // we need the trim as the LyX parser chokes on such spaces
1971 context.check_layout(os);
1972 os << "\n\\i \\" << t.cs() << "{"
1973 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
1977 else if (t.cs() == "ss") {
1978 context.check_layout(os);
1980 skip_braces(p); // eat {}
1983 else if (t.cs() == "i" || t.cs() == "j") {
1984 context.check_layout(os);
1985 os << "\\" << t.cs() << ' ';
1986 skip_braces(p); // eat {}
1989 else if (t.cs() == "\\") {
1990 context.check_layout(os);
1991 string const next = p.next_token().asInput();
1993 handle_ert(os, "\\\\" + p.getOpt(), context);
1994 else if (next == "*") {
1996 handle_ert(os, "\\\\*" + p.getOpt(), context);
1999 os << "\n\\newline\n";
2003 else if (t.cs() == "input" || t.cs() == "include"
2004 || t.cs() == "verbatiminput") {
2005 string name = '\\' + t.cs();
2006 if (t.cs() == "verbatiminput"
2007 && p.next_token().asInput() == "*")
2008 name += p.get_token().asInput();
2009 context.check_layout(os);
2010 begin_inset(os, "Include ");
2011 string filename(normalize_filename(p.getArg('{', '}')));
2012 string const path = getMasterFilePath();
2013 // We want to preserve relative / absolute filenames,
2014 // therefore path is only used for testing
2015 if (t.cs() == "include" &&
2016 !fs::exists(MakeAbsPath(filename, path))) {
2017 // The file extension is probably missing.
2018 // Now try to find it out.
2019 string const tex_name =
2020 find_file(filename, path,
2021 known_tex_extensions);
2022 if (!tex_name.empty())
2023 filename = tex_name;
2025 if (fs::exists(MakeAbsPath(filename, path))) {
2026 string const abstexname =
2027 MakeAbsPath(filename, path);
2028 string const abslyxname =
2029 ChangeExtension(abstexname, ".lyx");
2030 fix_relative_filename(filename);
2031 string const lyxname =
2032 ChangeExtension(filename, ".lyx");
2033 if (t.cs() != "verbatiminput" &&
2034 tex2lyx(abstexname, abslyxname)) {
2035 os << name << '{' << lyxname << "}\n";
2037 os << name << '{' << filename << "}\n";
2040 cerr << "Warning: Could not find included file '"
2041 << filename << "'." << endl;
2042 os << name << '{' << filename << "}\n";
2044 os << "preview false\n";
2048 else if (t.cs() == "bibliographystyle") {
2049 // store new bibliographystyle
2050 bibliographystyle = p.verbatim_item();
2051 // output new bibliographystyle.
2052 // This is only necessary if used in some other macro than \bibliography.
2053 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2056 else if (t.cs() == "bibliography") {
2057 context.check_layout(os);
2058 begin_inset(os, "LatexCommand ");
2060 // Do we have a bibliographystyle set?
2061 if (!bibliographystyle.empty()) {
2062 os << '[' << bibliographystyle << ']';
2064 os << '{' << p.verbatim_item() << "}\n";
2068 else if (t.cs() == "parbox")
2069 parse_box(p, os, FLAG_ITEM, outer, context, true);
2071 else if (t.cs() == "smallskip" ||
2072 t.cs() == "medskip" ||
2073 t.cs() == "bigskip" ||
2074 t.cs() == "vfill") {
2075 context.check_layout(os);
2076 begin_inset(os, "VSpace ");
2082 else if (t.cs() == "newpage") {
2083 context.check_layout(os);
2084 // FIXME: what about \\clearpage and \\pagebreak?
2085 os << "\n\\newpage\n";
2086 skip_braces(p); // eat {}
2089 else if (t.cs() == "newcommand" ||
2090 t.cs() == "providecommand" ||
2091 t.cs() == "renewcommand") {
2092 // these could be handled by parse_command(), but
2093 // we need to call add_known_command() here.
2094 string name = t.asInput();
2095 if (p.next_token().asInput() == "*") {
2096 // Starred form. Eat '*'
2100 string const command = p.verbatim_item();
2101 string const opt1 = p.getOpt();
2102 string const opt2 = p.getFullOpt();
2103 add_known_command(command, opt1, !opt2.empty());
2104 string const ert = name + '{' + command + '}' +
2106 '{' + p.verbatim_item() + '}';
2107 handle_ert(os, ert, context);
2110 else if (t.cs() == "vspace") {
2111 bool starred = false;
2112 if (p.next_token().asInput() == "*") {
2116 string const length = p.verbatim_item();
2119 bool valid = splitLatexLength(length, valstring, unit);
2120 bool known_vspace = false;
2121 bool known_unit = false;
2124 istringstream iss(valstring);
2127 if (unit == "\\smallskipamount") {
2129 known_vspace = true;
2130 } else if (unit == "\\medskipamount") {
2132 known_vspace = true;
2133 } else if (unit == "\\bigskipamount") {
2135 known_vspace = true;
2136 } else if (unit == "\\fill") {
2138 known_vspace = true;
2141 if (!known_vspace) {
2142 switch (unitFromString(unit)) {
2163 if (known_unit || known_vspace) {
2164 // Literal length or known variable
2165 context.check_layout(os);
2166 begin_inset(os, "VSpace ");
2174 // LyX can't handle other length variables in Inset VSpace
2175 string name = t.asInput();
2180 handle_ert(os, name + '{' + unit + '}', context);
2181 else if (value == -1.0)
2182 handle_ert(os, name + "{-" + unit + '}', context);
2184 handle_ert(os, name + '{' + valstring + unit + '}', context);
2186 handle_ert(os, name + '{' + length + '}', context);
2191 //cerr << "#: " << t << " mode: " << mode << endl;
2192 // heuristic: read up to next non-nested space
2194 string s = t.asInput();
2195 string z = p.verbatim_item();
2196 while (p.good() && z != " " && z.size()) {
2197 //cerr << "read: " << z << endl;
2199 z = p.verbatim_item();
2201 cerr << "found ERT: " << s << endl;
2202 handle_ert(os, s + ' ', context);
2204 string name = t.asInput();
2205 if (p.next_token().asInput() == "*") {
2206 // Starred commands like \vspace*{}
2207 p.get_token(); // Eat '*'
2210 if (! parse_command(name, p, os, outer, context))
2211 handle_ert(os, name, context);
2214 if (flags & FLAG_LEAVE) {
2215 flags &= ~FLAG_LEAVE;