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/tostr.h"
22 #include "support/filetools.h"
29 using lyx::support::rtrim;
30 using lyx::support::suffixIs;
31 using lyx::support::contains;
32 using lyx::support::subst;
39 using std::ostringstream;
40 using std::istringstream;
45 // thin wrapper around parse_text using a string
46 string parse_text(Parser & p, unsigned flags, const bool outer,
50 parse_text(p, os, flags, outer, context);
54 // parses a subdocument, usually useful in insets (whence the name)
55 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
58 Context newcontext(true, context.textclass);
59 parse_text(p, os, flags, outer, newcontext);
60 newcontext.check_end_layout(os);
64 // parses a paragraph snippet, useful for example for \emph{...}
65 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
68 Context newcontext(false, context.textclass);
69 parse_text(p, os, flags, outer, newcontext);
70 // should not be needed
71 newcontext.check_end_layout(os);
77 char const * known_latex_commands[] = { "ref", "cite", "label", "index",
78 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
80 // LaTeX names for quotes
81 char const * known_quotes[] = { "glqq", "grqq", "quotedblbase",
82 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
84 // the same as known_quotes with .lyx names
85 char const * known_coded_quotes[] = { "gld", "grd", "gld",
86 "grd", "gls", "fls", "frd", 0};
88 char const * known_sizes[] = { "tiny", "scriptsize", "footnotesize",
89 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
91 char const * known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
92 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
94 // splits "x=z, y=b" into a map
95 map<string, string> split_map(string const & s)
97 map<string, string> res;
100 for (size_t i = 0; i < v.size(); ++i) {
101 size_t const pos = v[i].find('=');
102 string const index = v[i].substr(0, pos);
103 string const value = v[i].substr(pos + 1, string::npos);
104 res[trim(index)] = trim(value);
111 * Split a LaTeX length into value and unit.
112 * The latter can be a real unit like "pt", or a latex length variable
113 * like "\textwidth". The unit may contain additional stuff like glue
114 * lengths, but we don't care, because such lengths are ERT anyway.
115 * \return true if \param value and \param unit are valid.
117 bool splitLatexLength(string const & len, string & value, string & unit)
121 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
122 //'4,5' is a valid LaTeX length number. Change it to '4.5'
123 string const length = subst(len, ',', '.');
124 if (i == string::npos)
127 if (len[0] == '\\') {
128 // We had something like \textwidth without a factor
134 value = trim(string(length, 0, i));
138 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
139 if (contains(len, '\\'))
140 unit = trim(string(len, i));
142 unit = lyx::support::lowercase(trim(string(len, i)));
147 /// A simple function to translate a latex length to something lyx can
148 /// understand. Not perfect, but rather best-effort.
149 bool translate_len(string const & length, string & valstring, string & unit)
151 if (!splitLatexLength(length, valstring, unit))
153 // LyX uses percent values
155 istringstream iss(valstring);
160 string const percentval = oss.str();
162 if (unit.empty() || unit[0] != '\\')
164 string::size_type const i = unit.find(' ');
165 string const endlen = (i == string::npos) ? string() : string(unit, i);
166 if (unit == "\\textwidth") {
167 valstring = percentval;
168 unit = "text%" + endlen;
169 } else if (unit == "\\columnwidth") {
170 valstring = percentval;
171 unit = "col%" + endlen;
172 } else if (unit == "\\paperwidth") {
173 valstring = percentval;
174 unit = "page%" + endlen;
175 } else if (unit == "\\linewidth") {
176 valstring = percentval;
177 unit = "line%" + endlen;
178 } else if (unit == "\\paperheight") {
179 valstring = percentval;
180 unit = "pheight%" + endlen;
181 } else if (unit == "\\textheight") {
182 valstring = percentval;
183 unit = "theight%" + endlen;
189 string translate_len(string const & length)
193 if (translate_len(length, value, unit))
195 // If the input is invalid, return what we have.
201 * Translates a LaTeX length into \param value, \param unit and
202 * \param special parts suitable for a box inset.
203 * The difference from translate_len() is that a box inset knows about
204 * some special "units" that are stored in \param special.
206 void translate_box_len(string const & length, string & value, string & unit, string & special)
208 if (translate_len(length, value, unit)) {
209 if (unit == "\\height" || unit == "\\depth" ||
210 unit == "\\totalheight" || unit == "\\width") {
211 special = unit.substr(1);
212 // The unit is not used, but LyX requires a dummy setting
224 void begin_inset(ostream & os, string const & name)
226 os << "\n\\begin_inset " << name;
230 void end_inset(ostream & os)
232 os << "\n\\end_inset \n\n";
236 void skip_braces(Parser & p)
238 if (p.next_token().cat() != catBegin)
241 if (p.next_token().cat() == catEnd) {
249 void handle_ert(ostream & os, string const & s, Context & context, bool check_layout = true)
252 // We must have a valid layout before outputting the ERT inset.
253 context.check_layout(os);
255 Context newcontext(true, context.textclass);
256 begin_inset(os, "ERT");
257 os << "\nstatus collapsed\n";
258 newcontext.check_layout(os);
259 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
261 os << "\n\\backslash \n";
262 else if (*it == '\n')
263 os << "\n\\newline \n";
267 newcontext.check_end_layout(os);
272 void handle_comment(ostream & os, string const & s, Context & context)
274 // TODO: Handle this better
275 Context newcontext(true, context.textclass);
276 begin_inset(os, "ERT");
277 os << "\nstatus collapsed\n";
278 newcontext.check_layout(os);
279 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
281 os << "\n\\backslash \n";
285 // make sure that our comment is the last thing on the line
287 newcontext.check_end_layout(os);
292 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
294 isLayout(string const name) : name_(name) {}
295 bool operator()(LyXLayout_ptr const & ptr) const {
296 return ptr->latexname() == name_;
303 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
306 LyXTextClass::const_iterator beg = textclass.begin();
307 LyXTextClass::const_iterator end = textclass.end();
309 LyXTextClass::const_iterator
310 it = std::find_if(beg, end, isLayout(name));
312 return (it == end) ? LyXLayout_ptr() : *it;
316 void eat_whitespace(Parser &, ostream &, Context &, bool);
319 void output_command_layout(ostream & os, Parser & p, bool outer,
320 Context & parent_context,
321 LyXLayout_ptr newlayout)
323 parent_context.check_end_layout(os);
324 Context context(true, parent_context.textclass, newlayout,
325 parent_context.layout);
326 context.check_deeper(os);
327 context.check_layout(os);
328 if (context.layout->optionalargs > 0) {
329 eat_whitespace(p, os, context, false);
330 if (p.next_token().character() == '[') {
331 p.get_token(); // eat '['
332 begin_inset(os, "OptArg\n");
333 os << "status collapsed\n\n";
334 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
336 eat_whitespace(p, os, context, false);
339 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
340 context.check_end_layout(os);
341 context.check_end_deeper(os);
342 // We don't need really a new paragraph, but
343 // we must make sure that the next item gets a \begin_layout.
344 parent_context.new_paragraph(os);
349 * Output a space if necessary.
350 * This function gets called for every whitespace token.
352 * We have three cases here:
353 * 1. A space must be suppressed. Example: The lyxcode case below
354 * 2. A space may be suppressed. Example: Spaces before "\par"
355 * 3. A space must not be suppressed. Example: A space between two words
357 * We currently handle only 1. and 3 and from 2. only the case of
358 * spaces before newlines as a side effect.
360 * 2. could be used to suppress as many spaces as possible. This has two effects:
361 * - Reimporting LyX generated LaTeX files changes almost no whitespace
362 * - Superflous whitespace from non LyX generated LaTeX files is removed.
363 * The drawback is that the logic inside the function becomes
364 * complicated, and that is the reason why it is not implemented.
366 void check_space(Parser const & p, ostream & os, Context & context)
368 Token const next = p.next_token();
369 Token const curr = p.curr_token();
370 // A space before a single newline and vice versa must be ignored
371 // LyX emits a newline before \end{lyxcode}.
372 // This newline must be ignored,
373 // otherwise LyX will add an additional protected space.
374 if (next.cat() == catSpace ||
375 next.cat() == catNewline ||
376 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
379 context.check_layout(os);
385 * Check whether \p command is a known command. If yes,
386 * handle the command with all arguments.
387 * \return true if the command was parsed, false otherwise.
389 bool parse_command(string const & command, Parser & p, ostream & os,
390 bool outer, Context & context)
392 if (known_commands.find(command) != known_commands.end()) {
393 vector<ArgumentType> const & template_arguments = known_commands[command];
394 string ert = command;
395 size_t no_arguments = template_arguments.size();
396 for (size_t i = 0; i < no_arguments; ++i) {
397 switch (template_arguments[i]) {
399 // This argument contains regular LaTeX
400 handle_ert(os, ert + '{', context);
401 parse_text(p, os, FLAG_ITEM, outer, context);
405 // This argument may contain special characters
406 ert += '{' + p.verbatim_item() + '}';
413 handle_ert(os, ert, context);
420 /// Parses a minipage or parbox
421 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
422 Context & parent_context, bool use_parbox)
426 string height_value = "0";
427 string height_unit = "pt";
428 string height_special = "none";
430 if (p.next_token().asInput() == "[") {
431 position = p.getArg('[', ']');
432 if (position != "t" && position != "c" && position != "b") {
434 cerr << "invalid position for minipage/parbox" << endl;
436 if (p.next_token().asInput() == "[") {
437 latex_height = p.getArg('[', ']');
438 translate_box_len(latex_height, height_value, height_unit, height_special);
440 if (p.next_token().asInput() == "[") {
441 inner_pos = p.getArg('[', ']');
442 if (inner_pos != "c" && inner_pos != "t" &&
443 inner_pos != "b" && inner_pos != "s") {
444 inner_pos = position;
445 cerr << "invalid inner_pos for minipage/parbox"
453 string const latex_width = p.verbatim_item();
454 translate_len(latex_width, width_value, width_unit);
455 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
456 // LyX can't handle length variables
461 ss << "\\begin{minipage}";
462 if (!position.empty())
463 ss << '[' << position << ']';
464 if (!latex_height.empty())
465 ss << '[' << latex_height << ']';
466 if (!inner_pos.empty())
467 ss << '[' << inner_pos << ']';
468 ss << "{" << latex_width << "}";
471 handle_ert(os, ss.str(), parent_context);
472 parent_context.new_paragraph(os);
473 parse_text_in_inset(p, os, flags, outer, parent_context);
475 handle_ert(os, "}", parent_context);
477 handle_ert(os, "\\end{minipage}", parent_context);
479 // LyX does not like empty positions, so we have
480 // to set them to the LaTeX default values here.
481 if (position.empty())
483 if (inner_pos.empty())
484 inner_pos = position;
485 parent_context.check_layout(os);
486 begin_inset(os, "Box Frameless\n");
487 os << "position \"" << position << "\"\n";
488 os << "hor_pos \"c\"\n";
489 os << "has_inner_box 1\n";
490 os << "inner_pos \"" << inner_pos << "\"\n";
491 os << "use_parbox " << use_parbox << "\n";
492 os << "width \"" << width_value << width_unit << "\"\n";
493 os << "special \"none\"\n";
494 os << "height \"" << height_value << height_unit << "\"\n";
495 os << "height_special \"" << height_special << "\"\n";
496 os << "status open\n\n";
497 parse_text_in_inset(p, os, flags, outer, parent_context);
499 #ifdef PRESERVE_LAYOUT
500 // lyx puts a % after the end of the minipage
501 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
503 //handle_comment(os, "%dummy", parent_context);
506 parent_context.new_paragraph(os);
508 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
509 //handle_comment(os, "%dummy", parent_context);
512 // We add a protected space if something real follows
513 if (p.good() && p.next_token().cat() != catComment) {
514 os << "\\InsetSpace ~\n";
522 void parse_environment(Parser & p, ostream & os, bool outer,
523 Context & parent_context)
525 LyXLayout_ptr newlayout;
526 string const name = p.getArg('{', '}');
527 const bool is_starred = suffixIs(name, '*');
528 string const unstarred_name = rtrim(name, "*");
529 eat_whitespace(p, os, parent_context, false);
530 active_environments.push_back(name);
532 if (is_math_env(name)) {
533 parent_context.check_layout(os);
534 begin_inset(os, "Formula ");
535 os << "\\begin{" << name << "}";
536 parse_math(p, os, FLAG_END, MATH_MODE);
537 os << "\\end{" << name << "}";
541 else if (name == "tabular") {
542 parent_context.check_layout(os);
543 begin_inset(os, "Tabular ");
544 handle_tabular(p, os, parent_context);
548 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
549 parent_context.check_layout(os);
550 begin_inset(os, "Float " + unstarred_name + "\n");
551 if (p.next_token().asInput() == "[") {
552 os << "placement " << p.getArg('[', ']') << '\n';
554 os << "wide " << tostr(is_starred)
555 << "\nstatus open\n\n";
556 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
558 // We don't need really a new paragraph, but
559 // we must make sure that the next item gets a \begin_layout.
560 parent_context.new_paragraph(os);
563 else if (name == "minipage")
564 parse_box(p, os, FLAG_END, outer, parent_context, false);
566 // Alignment settings
567 else if (name == "center" || name == "flushleft" || name == "flushright" ||
568 name == "centering" || name == "raggedright" || name == "raggedleft") {
569 // We must begin a new paragraph if not already done
570 if (! parent_context.atParagraphStart()) {
571 parent_context.check_end_layout(os);
572 parent_context.new_paragraph(os);
574 if (name == "flushleft" || name == "raggedright")
575 parent_context.add_extra_stuff("\\align left ");
576 else if (name == "flushright" || name == "raggedleft")
577 parent_context.add_extra_stuff("\\align right ");
579 parent_context.add_extra_stuff("\\align center ");
580 parse_text(p, os, FLAG_END, outer, parent_context);
581 // Just in case the environment is empty ..
582 parent_context.extra_stuff.erase();
583 // We must begin a new paragraph to reset the alignment
584 parent_context.new_paragraph(os);
587 // The single '=' is meant here.
588 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
589 newlayout->isEnvironment()) {
590 Context context(true, parent_context.textclass, newlayout,
591 parent_context.layout);
592 parent_context.check_end_layout(os);
593 switch (context.layout->latextype) {
594 case LATEX_LIST_ENVIRONMENT:
595 context.extra_stuff = "\\labelwidthstring "
596 + p.verbatim_item() + '\n';
599 case LATEX_BIB_ENVIRONMENT:
600 p.verbatim_item(); // swallow next arg
606 context.check_deeper(os);
607 parse_text(p, os, FLAG_END, outer, context);
608 context.check_end_layout(os);
609 context.check_end_deeper(os);
610 parent_context.new_paragraph(os);
613 else if (name == "appendix") {
614 // This is no good latex style, but it works and is used in some documents...
615 parent_context.check_end_layout(os);
616 Context context(true, parent_context.textclass, parent_context.layout,
617 parent_context.layout);
618 context.check_layout(os);
619 os << "\\start_of_appendix\n";
620 parse_text(p, os, FLAG_END, outer, context);
621 context.check_end_layout(os);
624 else if (name == "comment") {
625 parent_context.check_layout(os);
626 begin_inset(os, "Note Comment\n");
627 os << "status open\n";
628 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
632 else if (name == "lyxgreyedout") {
633 parent_context.check_layout(os);
634 begin_inset(os, "Note Greyedout\n");
635 os << "status open\n";
636 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
640 else if (name == "tabbing") {
641 // We need to remember that we have to handle '\=' specially
642 handle_ert(os, "\\begin{" + name + "}", parent_context);
643 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
644 handle_ert(os, "\\end{" + name + "}", parent_context);
648 handle_ert(os, "\\begin{" + name + "}", parent_context);
649 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
650 handle_ert(os, "\\end{" + name + "}", parent_context);
653 active_environments.pop_back();
658 /// parses a comment and outputs it to \p os.
659 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
661 BOOST_ASSERT(t.cat() == catComment);
662 context.check_layout(os);
663 if (!t.cs().empty()) {
664 handle_comment(os, '%' + t.cs(), context);
665 if (p.next_token().cat() == catNewline) {
666 // A newline after a comment line starts a new
668 if(!context.atParagraphStart()) {
669 // Only start a new paragraph if not already
670 // done (we might get called recursively)
671 context.new_paragraph(os);
673 eat_whitespace(p, os, context, true);
683 * Reads spaces and comments until the first non-space, non-comment token.
684 * New paragraphs (double newlines or \\par) are handled like simple spaces
685 * if \p eatParagraph is true.
686 * Spaces are skipped, but comments are written to \p os.
688 void eat_whitespace(Parser & p, ostream & os, Context & context,
692 Token const & t = p.get_token();
693 if (t.cat() == catComment)
694 parse_comment(p, os, t, context);
695 else if ((! eatParagraph && p.isParagraph()) ||
696 (t.cat() != catSpace && t.cat() != catNewline)) {
703 } // anonymous namespace
706 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
709 LyXLayout_ptr newlayout;
710 // Store the latest bibliographystyle (needed for bibtex inset)
711 string bibliographystyle;
713 Token const & t = p.get_token();
716 cerr << "t: " << t << " flags: " << flags << "\n";
719 if (flags & FLAG_ITEM) {
720 if (t.cat() == catSpace)
724 if (t.cat() == catBegin) {
725 // skip the brace and collect everything to the next matching
727 flags |= FLAG_BRACE_LAST;
731 // handle only this single token, leave the loop if done
735 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
741 if (t.cat() == catMath) {
742 // we are inside some text mode thingy, so opening new math is allowed
743 context.check_layout(os);
744 begin_inset(os, "Formula ");
745 Token const & n = p.get_token();
746 if (n.cat() == catMath && outer) {
747 // TeX's $$...$$ syntax for displayed math
749 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
751 p.get_token(); // skip the second '$' token
753 // simple $...$ stuff
756 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
762 else if (t.cat() == catSuper || t.cat() == catSub)
763 cerr << "catcode " << t << " illegal in text mode\n";
765 // Basic support for english quotes. This should be
766 // extended to other quotes, but is not so easy (a
767 // left english quote is the same as a right german
769 else if (t.asInput() == "`"
770 && p.next_token().asInput() == "`") {
771 context.check_layout(os);
772 begin_inset(os, "Quotes ");
778 else if (t.asInput() == "'"
779 && p.next_token().asInput() == "'") {
780 context.check_layout(os);
781 begin_inset(os, "Quotes ");
788 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
789 check_space(p, os, context);
791 else if (t.cat() == catLetter ||
792 t.cat() == catOther ||
793 t.cat() == catAlign ||
794 t.cat() == catParameter) {
795 context.check_layout(os);
799 else if (p.isParagraph()) {
800 context.new_paragraph(os);
801 eat_whitespace(p, os, context, true);
804 else if (t.cat() == catActive) {
805 context.check_layout(os);
806 if (t.character() == '~') {
807 if (context.layout->free_spacing)
810 os << "\\InsetSpace ~\n";
815 else if (t.cat() == catBegin) {
816 // special handling of size changes
817 context.check_layout(os);
818 bool const is_size = is_known(p.next_token().cs(), known_sizes);
819 Token const prev = p.prev_token();
820 string const s = parse_text(p, FLAG_BRACE_LAST, outer, context);
821 if (s.empty() && (p.next_token().character() == '`' ||
822 (prev.character() == '-' && p.next_token().character())))
823 ; // ignore it in {}`` or -{}-
824 else if (is_size || s == "[" || s == "]" || s == "*")
827 handle_ert(os, "{", context, false);
828 // s will end the current layout and begin a new one if necessary
830 handle_ert(os, "}", context);
834 else if (t.cat() == catEnd) {
835 if (flags & FLAG_BRACE_LAST) {
838 cerr << "stray '}' in text\n";
839 handle_ert(os, "}", context);
842 else if (t.cat() == catComment)
843 parse_comment(p, os, t, context);
849 else if (t.cs() == "(") {
850 context.check_layout(os);
851 begin_inset(os, "Formula");
853 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
858 else if (t.cs() == "[") {
859 context.check_layout(os);
860 begin_inset(os, "Formula");
862 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
867 else if (t.cs() == "begin")
868 parse_environment(p, os, outer, context);
870 else if (t.cs() == "end") {
871 if (flags & FLAG_END) {
872 // eat environment name
873 string const name = p.getArg('{', '}');
874 if (name != active_environment())
875 cerr << "\\end{" + name + "} does not match \\begin{"
876 + active_environment() + "}\n";
879 p.error("found 'end' unexpectedly");
882 else if (t.cs() == "item") {
886 if (p.next_token().character() == '[') {
887 p.get_token(); // eat '['
888 Context newcontext(false, context.textclass);
889 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
893 context.check_layout(os);
895 if (context.layout->labeltype != LABEL_MANUAL) {
896 // lyx does not support \item[\mybullet] in itemize environments
897 handle_ert(os, "[", context);
899 handle_ert(os, "]", context);
900 } else if (!s.empty()) {
901 // The space is needed to separate the item from the rest of the sentence.
903 eat_whitespace(p, os, context, false);
908 else if (t.cs() == "bibitem") {
910 context.check_layout(os);
913 os << '{' << p.verbatim_item() << '}' << "\n";
916 else if (t.cs() == "def") {
917 context.check_layout(os);
918 eat_whitespace(p, os, context, false);
919 string name = p.get_token().cs();
920 while (p.next_token().cat() != catBegin)
921 name += p.get_token().asString();
922 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
925 else if (t.cs() == "noindent") {
927 context.add_extra_stuff("\\noindent ");
930 else if (t.cs() == "appendix") {
932 context.add_extra_stuff("\\start_of_appendix ");
935 // Must attempt to parse "Section*" before "Section".
936 else if ((p.next_token().asInput() == "*") &&
937 // The single '=' is meant here.
938 (newlayout = findLayout(context.textclass,
939 t.cs() + '*')).get() &&
940 newlayout->isCommand()) {
942 output_command_layout(os, p, outer, context, newlayout);
946 // The single '=' is meant here.
947 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
948 newlayout->isCommand()) {
949 output_command_layout(os, p, outer, context, newlayout);
953 else if (t.cs() == "includegraphics") {
954 map<string, string> opts = split_map(p.getArg('[', ']'));
955 string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
957 context.check_layout(os);
958 begin_inset(os, "Graphics ");
959 os << "\n\tfilename " << name << '\n';
960 if (opts.find("width") != opts.end())
962 << translate_len(opts["width"]) << '\n';
963 if (opts.find("height") != opts.end())
965 << translate_len(opts["height"]) << '\n';
966 if (opts.find("scale") != opts.end()) {
967 istringstream iss(opts["scale"]);
971 os << "\tscale " << val << '\n';
973 if (opts.find("angle") != opts.end())
974 os << "\trotateAngle "
975 << opts["angle"] << '\n';
976 if (opts.find("origin") != opts.end()) {
978 string const opt = opts["origin"];
979 if (opt.find('l') != string::npos) ss << "left";
980 if (opt.find('r') != string::npos) ss << "right";
981 if (opt.find('c') != string::npos) ss << "center";
982 if (opt.find('t') != string::npos) ss << "Top";
983 if (opt.find('b') != string::npos) ss << "Bottom";
984 if (opt.find('B') != string::npos) ss << "Baseline";
985 if (!ss.str().empty())
986 os << "\trotateOrigin " << ss.str() << '\n';
988 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
990 if (opts.find("keepaspectratio") != opts.end())
991 os << "\tkeepAspectRatio\n";
992 if (opts.find("clip") != opts.end())
994 if (opts.find("draft") != opts.end())
996 if (opts.find("bb") != opts.end())
997 os << "\tBoundingBox "
998 << opts["bb"] << '\n';
999 int numberOfbbOptions = 0;
1000 if (opts.find("bbllx") != opts.end())
1001 numberOfbbOptions++;
1002 if (opts.find("bblly") != opts.end())
1003 numberOfbbOptions++;
1004 if (opts.find("bburx") != opts.end())
1005 numberOfbbOptions++;
1006 if (opts.find("bbury") != opts.end())
1007 numberOfbbOptions++;
1008 if (numberOfbbOptions == 4)
1009 os << "\tBoundingBox "
1010 << opts["bbllx"] << opts["bblly"]
1011 << opts["bburx"] << opts["bbury"] << '\n';
1012 else if (numberOfbbOptions > 0)
1013 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1014 numberOfbbOptions = 0;
1015 if (opts.find("natwidth") != opts.end())
1016 numberOfbbOptions++;
1017 if (opts.find("natheight") != opts.end())
1018 numberOfbbOptions++;
1019 if (numberOfbbOptions == 2)
1020 os << "\tBoundingBox 0bp 0bp "
1021 << opts["natwidth"] << opts["natheight"] << '\n';
1022 else if (numberOfbbOptions > 0)
1023 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1024 ostringstream special;
1025 if (opts.find("hiresbb") != opts.end())
1026 special << "hiresbb,";
1027 if (opts.find("trim") != opts.end())
1029 if (opts.find("viewport") != opts.end())
1030 special << "viewport=" << opts["viewport"] << ',';
1031 if (opts.find("totalheight") != opts.end())
1032 special << "totalheight=" << opts["totalheight"] << ',';
1033 if (opts.find("type") != opts.end())
1034 special << "type=" << opts["type"] << ',';
1035 if (opts.find("ext") != opts.end())
1036 special << "ext=" << opts["ext"] << ',';
1037 if (opts.find("read") != opts.end())
1038 special << "read=" << opts["read"] << ',';
1039 if (opts.find("command") != opts.end())
1040 special << "command=" << opts["command"] << ',';
1041 string s_special = special.str();
1042 if (!s_special.empty()) {
1043 // We had special arguments. Remove the trailing ','.
1044 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1046 // TODO: Handle the unknown settings better.
1047 // Warn about invalid options.
1048 // Check whether some option was given twice.
1052 else if (t.cs() == "footnote") {
1054 context.check_layout(os);
1055 begin_inset(os, "Foot\n");
1056 os << "status collapsed\n\n";
1057 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1061 else if (t.cs() == "marginpar") {
1063 context.check_layout(os);
1064 begin_inset(os, "Marginal\n");
1065 os << "status collapsed\n\n";
1066 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1070 else if (t.cs() == "ensuremath") {
1072 context.check_layout(os);
1073 Context newcontext(false, context.textclass);
1074 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1075 if (s == "±" || s == "³" || s == "²" || s == "µ")
1078 handle_ert(os, "\\ensuremath{" + s + "}",
1082 else if (t.cs() == "hfill") {
1083 context.check_layout(os);
1084 os << "\n\\hfill \n";
1089 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1091 skip_braces(p); // swallow this
1094 else if (t.cs() == "tableofcontents") {
1096 context.check_layout(os);
1097 begin_inset(os, "LatexCommand \\tableofcontents\n");
1099 skip_braces(p); // swallow this
1102 else if (t.cs() == "listoffigures") {
1104 context.check_layout(os);
1105 begin_inset(os, "FloatList figure\n");
1107 skip_braces(p); // swallow this
1110 else if (t.cs() == "listoftables") {
1112 context.check_layout(os);
1113 begin_inset(os, "FloatList table\n");
1115 skip_braces(p); // swallow this
1118 else if (t.cs() == "listof") {
1119 p.skip_spaces(true);
1120 string const name = p.get_token().asString();
1121 if (context.textclass.floats().typeExist(name)) {
1122 context.check_layout(os);
1123 begin_inset(os, "FloatList ");
1126 p.get_token(); // swallow second arg
1128 handle_ert(os, "\\listof{" + name + "}", context);
1131 else if (t.cs() == "textrm") {
1132 context.check_layout(os);
1133 os << "\n\\family roman \n";
1134 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1135 os << "\n\\family default \n";
1138 else if (t.cs() == "textsf") {
1139 context.check_layout(os);
1140 os << "\n\\family sans \n";
1141 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1142 os << "\n\\family default \n";
1145 else if (t.cs() == "textsl") {
1146 context.check_layout(os);
1147 os << "\n\\shape slanted \n";
1148 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1149 os << "\n\\shape default \n";
1152 else if (t.cs() == "texttt") {
1153 context.check_layout(os);
1154 os << "\n\\family typewriter \n";
1155 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1156 os << "\n\\family default \n";
1159 else if (t.cs() == "textit") {
1160 context.check_layout(os);
1161 os << "\n\\shape italic \n";
1162 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1163 os << "\n\\shape default \n";
1166 else if (t.cs() == "textsc") {
1167 context.check_layout(os);
1168 os << "\n\\noun on \n";
1169 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1170 os << "\n\\noun default \n";
1173 else if (t.cs() == "textbf") {
1174 context.check_layout(os);
1175 os << "\n\\series bold \n";
1176 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1177 os << "\n\\series default \n";
1180 else if (t.cs() == "underbar") {
1181 context.check_layout(os);
1182 os << "\n\\bar under \n";
1183 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1184 os << "\n\\bar default \n";
1187 else if (t.cs() == "emph" || t.cs() == "noun") {
1188 context.check_layout(os);
1189 os << "\n\\" << t.cs() << " on \n";
1190 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1191 os << "\n\\" << t.cs() << " default \n";
1194 else if (is_known(t.cs(), known_latex_commands)) {
1195 context.check_layout(os);
1196 begin_inset(os, "LatexCommand ");
1197 os << '\\' << t.cs();
1200 os << '{' << p.verbatim_item() << "}\n";
1204 else if (is_known(t.cs(), known_quotes)) {
1205 char const ** where = is_known(t.cs(), known_quotes);
1206 context.check_layout(os);
1207 begin_inset(os, "Quotes ");
1208 os << known_coded_quotes[where - known_quotes];
1210 // LyX adds {} after the quote, so we have to eat
1211 // spaces here if there are any before a possible
1213 eat_whitespace(p, os, context, false);
1217 else if (is_known(t.cs(), known_sizes)) {
1218 char const ** where = is_known(t.cs(), known_sizes);
1219 context.check_layout(os);
1220 os << "\n\\size " << known_coded_sizes[where - known_sizes] << "\n";
1221 eat_whitespace(p, os, context, false);
1224 else if (t.cs() == "LyX" || t.cs() == "TeX"
1225 || t.cs() == "LaTeX") {
1226 context.check_layout(os);
1228 skip_braces(p); // eat {}
1231 else if (t.cs() == "LaTeXe") {
1232 context.check_layout(os);
1234 skip_braces(p); // eat {}
1237 else if (t.cs() == "ldots") {
1238 context.check_layout(os);
1240 os << "\\SpecialChar \\ldots{}\n";
1243 else if (t.cs() == "lyxarrow") {
1244 context.check_layout(os);
1245 os << "\\SpecialChar \\menuseparator\n";
1249 else if (t.cs() == "textcompwordmark") {
1250 context.check_layout(os);
1251 os << "\\SpecialChar \\textcompwordmark{}\n";
1255 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1256 context.check_layout(os);
1257 os << "\\SpecialChar \\@.\n";
1261 else if (t.cs() == "-") {
1262 context.check_layout(os);
1263 os << "\\SpecialChar \\-\n";
1266 else if (t.cs() == "textasciitilde") {
1267 context.check_layout(os);
1272 else if (t.cs() == "textasciicircum") {
1273 context.check_layout(os);
1278 else if (t.cs() == "textbackslash") {
1279 context.check_layout(os);
1280 os << "\n\\backslash \n";
1284 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1285 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1287 context.check_layout(os);
1291 else if (t.cs() == "char") {
1292 context.check_layout(os);
1293 if (p.next_token().character() == '`') {
1295 if (p.next_token().cs() == "\"") {
1300 handle_ert(os, "\\char`", context);
1303 handle_ert(os, "\\char", context);
1307 else if (t.cs() == "\"") {
1308 context.check_layout(os);
1309 string const name = p.verbatim_item();
1310 if (name == "a") os << 'ä';
1311 else if (name == "o") os << 'ö';
1312 else if (name == "u") os << 'ü';
1313 else if (name == "A") os << 'Ä';
1314 else if (name == "O") os << 'Ö';
1315 else if (name == "U") os << 'Ü';
1316 else handle_ert(os, "\"{" + name + "}", context);
1319 // Problem: \= creates a tabstop inside the tabbing environment
1320 // and else an accent. In the latter case we really would want
1321 // \={o} instead of \= o.
1322 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1323 handle_ert(os, t.asInput(), context);
1325 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1326 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1327 // we need the trim as the LyX parser chokes on such spaces
1328 context.check_layout(os);
1329 os << "\n\\i \\" << t.cs() << "{"
1330 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1333 else if (t.cs() == "ss") {
1334 context.check_layout(os);
1338 else if (t.cs() == "i" || t.cs() == "j") {
1339 context.check_layout(os);
1340 os << "\\" << t.cs() << ' ';
1343 else if (t.cs() == "\\") {
1344 context.check_layout(os);
1345 string const next = p.next_token().asInput();
1347 handle_ert(os, "\\\\" + p.getOpt(), context);
1348 else if (next == "*") {
1350 handle_ert(os, "\\\\*" + p.getOpt(), context);
1353 os << "\n\\newline \n";
1357 else if (t.cs() == "input" || t.cs() == "include"
1358 || t.cs() == "verbatiminput") {
1359 string name = '\\' + t.cs();
1360 if (t.cs() == "verbatiminput"
1361 && p.next_token().asInput() == "*")
1362 name += p.get_token().asInput();
1363 context.check_layout(os);
1364 begin_inset(os, "Include ");
1365 string filename(p.getArg('{', '}'));
1366 string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1367 if (tex2lyx(filename, lyxname)) {
1368 os << name << '{' << lyxname << "}\n";
1370 os << name << '{' << filename << "}\n";
1372 os << "preview false\n";
1376 else if (t.cs() == "fancyhead") {
1377 context.check_layout(os);
1379 ss << "\\fancyhead";
1381 ss << '{' << p.verbatim_item() << "}\n";
1382 handle_ert(os, ss.str(), context);
1385 else if (t.cs() == "bibliographystyle") {
1386 // store new bibliographystyle
1387 bibliographystyle = p.verbatim_item();
1388 // output new bibliographystyle.
1389 // This is only necessary if used in some other macro than \bibliography.
1390 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1393 else if (t.cs() == "bibliography") {
1394 context.check_layout(os);
1395 begin_inset(os, "LatexCommand ");
1397 // Do we have a bibliographystyle set?
1398 if (!bibliographystyle.empty()) {
1399 os << '[' << bibliographystyle << ']';
1401 os << '{' << p.verbatim_item() << "}\n";
1405 else if (t.cs() == "parbox")
1406 parse_box(p, os, FLAG_ITEM, outer, context, true);
1408 else if (t.cs() == "smallskip" ||
1409 t.cs() == "medskip" ||
1410 t.cs() == "bigskip" ||
1411 t.cs() == "vfill") {
1412 context.check_layout(os);
1413 begin_inset(os, "VSpace ");
1419 else if (t.cs() == "vspace") {
1420 bool starred = false;
1421 if (p.next_token().asInput() == "*") {
1425 string const length = p.verbatim_item();
1428 bool valid = splitLatexLength(length, valstring, unit);
1429 bool known_vspace = false;
1430 bool known_unit = false;
1433 istringstream iss(valstring);
1436 if (unit == "\\smallskipamount") {
1438 known_vspace = true;
1439 } else if (unit == "\\medskipamount") {
1441 known_vspace = true;
1442 } else if (unit == "\\bigskipamount") {
1444 known_vspace = true;
1445 } else if (unit == "\\fill") {
1447 known_vspace = true;
1450 if (!known_vspace) {
1451 switch (unitFromString(unit)) {
1472 if (known_unit || known_vspace) {
1473 // Literal length or known variable
1474 context.check_layout(os);
1475 begin_inset(os, "VSpace ");
1483 // LyX can't handle other length variables in Inset VSpace
1484 string name = t.asInput();
1489 handle_ert(os, name + '{' + unit + '}', context);
1490 else if (value == -1.0)
1491 handle_ert(os, name + "{-" + unit + '}', context);
1493 handle_ert(os, name + '{' + valstring + unit + '}', context);
1495 handle_ert(os, name + '{' + length + '}', context);
1500 //cerr << "#: " << t << " mode: " << mode << endl;
1501 // heuristic: read up to next non-nested space
1503 string s = t.asInput();
1504 string z = p.verbatim_item();
1505 while (p.good() && z != " " && z.size()) {
1506 //cerr << "read: " << z << endl;
1508 z = p.verbatim_item();
1510 cerr << "found ERT: " << s << endl;
1511 handle_ert(os, s + ' ', context);
1513 string name = t.asInput();
1514 if (p.next_token().asInput() == "*") {
1515 // Starred commands like \vspace*{}
1516 p.get_token(); // Eat '*'
1519 if (! parse_command(name, p, os, outer, context))
1520 handle_ert(os, name, context);
1523 if (flags & FLAG_LEAVE) {
1524 flags &= ~FLAG_LEAVE;