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 if (parent_context.deeper_paragraph) {
327 // We are beginning a nested environment after a
328 // deeper paragraph inside the outer list environment.
329 // Therefore we don't need to output a "begin deeper".
330 context.need_end_deeper = true;
332 context.check_deeper(os);
333 context.check_layout(os);
334 if (context.layout->optionalargs > 0) {
335 eat_whitespace(p, os, context, false);
336 if (p.next_token().character() == '[') {
337 p.get_token(); // eat '['
338 begin_inset(os, "OptArg\n");
339 os << "status collapsed\n\n";
340 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
342 eat_whitespace(p, os, context, false);
345 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
346 context.check_end_layout(os);
347 if (parent_context.deeper_paragraph) {
348 // We must suppress the "end deeper" because we
349 // suppressed the "begin deeper" above.
350 context.need_end_deeper = false;
352 context.check_end_deeper(os);
353 // We don't need really a new paragraph, but
354 // we must make sure that the next item gets a \begin_layout.
355 parent_context.new_paragraph(os);
360 * Output a space if necessary.
361 * This function gets called for every whitespace token.
363 * We have three cases here:
364 * 1. A space must be suppressed. Example: The lyxcode case below
365 * 2. A space may be suppressed. Example: Spaces before "\par"
366 * 3. A space must not be suppressed. Example: A space between two words
368 * We currently handle only 1. and 3 and from 2. only the case of
369 * spaces before newlines as a side effect.
371 * 2. could be used to suppress as many spaces as possible. This has two effects:
372 * - Reimporting LyX generated LaTeX files changes almost no whitespace
373 * - Superflous whitespace from non LyX generated LaTeX files is removed.
374 * The drawback is that the logic inside the function becomes
375 * complicated, and that is the reason why it is not implemented.
377 void check_space(Parser const & p, ostream & os, Context & context)
379 Token const next = p.next_token();
380 Token const curr = p.curr_token();
381 // A space before a single newline and vice versa must be ignored
382 // LyX emits a newline before \end{lyxcode}.
383 // This newline must be ignored,
384 // otherwise LyX will add an additional protected space.
385 if (next.cat() == catSpace ||
386 next.cat() == catNewline ||
387 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
390 context.check_layout(os);
396 * Check whether \p command is a known command. If yes,
397 * handle the command with all arguments.
398 * \return true if the command was parsed, false otherwise.
400 bool parse_command(string const & command, Parser & p, ostream & os,
401 bool outer, Context & context)
403 if (known_commands.find(command) != known_commands.end()) {
404 vector<ArgumentType> const & template_arguments = known_commands[command];
405 string ert = command;
406 size_t no_arguments = template_arguments.size();
407 for (size_t i = 0; i < no_arguments; ++i) {
408 switch (template_arguments[i]) {
410 // This argument contains regular LaTeX
411 handle_ert(os, ert + '{', context);
412 parse_text(p, os, FLAG_ITEM, outer, context);
416 // This argument may contain special characters
417 ert += '{' + p.verbatim_item() + '}';
424 handle_ert(os, ert, context);
431 /// Parses a minipage or parbox
432 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
433 Context & parent_context, bool use_parbox)
437 string height_value = "0";
438 string height_unit = "pt";
439 string height_special = "none";
441 if (p.next_token().asInput() == "[") {
442 position = p.getArg('[', ']');
443 if (position != "t" && position != "c" && position != "b") {
445 cerr << "invalid position for minipage/parbox" << endl;
447 if (p.next_token().asInput() == "[") {
448 latex_height = p.getArg('[', ']');
449 translate_box_len(latex_height, height_value, height_unit, height_special);
451 if (p.next_token().asInput() == "[") {
452 inner_pos = p.getArg('[', ']');
453 if (inner_pos != "c" && inner_pos != "t" &&
454 inner_pos != "b" && inner_pos != "s") {
455 inner_pos = position;
456 cerr << "invalid inner_pos for minipage/parbox"
464 string const latex_width = p.verbatim_item();
465 translate_len(latex_width, width_value, width_unit);
466 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
467 // LyX can't handle length variables
472 ss << "\\begin{minipage}";
473 if (!position.empty())
474 ss << '[' << position << ']';
475 if (!latex_height.empty())
476 ss << '[' << latex_height << ']';
477 if (!inner_pos.empty())
478 ss << '[' << inner_pos << ']';
479 ss << "{" << latex_width << "}";
482 handle_ert(os, ss.str(), parent_context);
483 parent_context.new_paragraph(os);
484 parse_text_in_inset(p, os, flags, outer, parent_context);
486 handle_ert(os, "}", parent_context);
488 handle_ert(os, "\\end{minipage}", parent_context);
490 // LyX does not like empty positions, so we have
491 // to set them to the LaTeX default values here.
492 if (position.empty())
494 if (inner_pos.empty())
495 inner_pos = position;
496 parent_context.check_layout(os);
497 begin_inset(os, "Box Frameless\n");
498 os << "position \"" << position << "\"\n";
499 os << "hor_pos \"c\"\n";
500 os << "has_inner_box 1\n";
501 os << "inner_pos \"" << inner_pos << "\"\n";
502 os << "use_parbox " << use_parbox << "\n";
503 os << "width \"" << width_value << width_unit << "\"\n";
504 os << "special \"none\"\n";
505 os << "height \"" << height_value << height_unit << "\"\n";
506 os << "height_special \"" << height_special << "\"\n";
507 os << "status open\n\n";
508 parse_text_in_inset(p, os, flags, outer, parent_context);
510 #ifdef PRESERVE_LAYOUT
511 // lyx puts a % after the end of the minipage
512 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
514 //handle_comment(os, "%dummy", parent_context);
517 parent_context.new_paragraph(os);
519 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
520 //handle_comment(os, "%dummy", parent_context);
523 // We add a protected space if something real follows
524 if (p.good() && p.next_token().cat() != catComment) {
525 os << "\\InsetSpace ~\n";
533 void parse_environment(Parser & p, ostream & os, bool outer,
534 Context & parent_context)
536 LyXLayout_ptr newlayout;
537 string const name = p.getArg('{', '}');
538 const bool is_starred = suffixIs(name, '*');
539 string const unstarred_name = rtrim(name, "*");
540 eat_whitespace(p, os, parent_context, false);
541 active_environments.push_back(name);
543 if (is_math_env(name)) {
544 parent_context.check_layout(os);
545 begin_inset(os, "Formula ");
546 os << "\\begin{" << name << "}";
547 parse_math(p, os, FLAG_END, MATH_MODE);
548 os << "\\end{" << name << "}";
552 else if (name == "tabular") {
553 parent_context.check_layout(os);
554 begin_inset(os, "Tabular ");
555 handle_tabular(p, os, parent_context);
559 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
560 parent_context.check_layout(os);
561 begin_inset(os, "Float " + unstarred_name + "\n");
562 if (p.next_token().asInput() == "[") {
563 os << "placement " << p.getArg('[', ']') << '\n';
565 os << "wide " << tostr(is_starred)
566 << "\nstatus open\n\n";
567 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
569 // We don't need really a new paragraph, but
570 // we must make sure that the next item gets a \begin_layout.
571 parent_context.new_paragraph(os);
574 else if (name == "minipage")
575 parse_box(p, os, FLAG_END, outer, parent_context, false);
577 // Alignment settings
578 else if (name == "center" || name == "flushleft" || name == "flushright" ||
579 name == "centering" || name == "raggedright" || name == "raggedleft") {
580 // We must begin a new paragraph if not already done
581 if (! parent_context.atParagraphStart()) {
582 parent_context.check_end_layout(os);
583 parent_context.new_paragraph(os);
585 if (name == "flushleft" || name == "raggedright")
586 parent_context.add_extra_stuff("\\align left ");
587 else if (name == "flushright" || name == "raggedleft")
588 parent_context.add_extra_stuff("\\align right ");
590 parent_context.add_extra_stuff("\\align center ");
591 parse_text(p, os, FLAG_END, outer, parent_context);
592 // Just in case the environment is empty ..
593 parent_context.extra_stuff.erase();
594 // We must begin a new paragraph to reset the alignment
595 parent_context.new_paragraph(os);
598 // The single '=' is meant here.
599 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
600 newlayout->isEnvironment()) {
601 Context context(true, parent_context.textclass, newlayout,
602 parent_context.layout);
603 if (parent_context.deeper_paragraph) {
604 // We are beginning a nested environment after a
605 // deeper paragraph inside the outer list environment.
606 // Therefore we don't need to output a "begin deeper".
607 context.need_end_deeper = true;
609 parent_context.check_end_layout(os);
610 switch (context.layout->latextype) {
611 case LATEX_LIST_ENVIRONMENT:
612 context.extra_stuff = "\\labelwidthstring "
613 + p.verbatim_item() + '\n';
616 case LATEX_BIB_ENVIRONMENT:
617 p.verbatim_item(); // swallow next arg
623 context.check_deeper(os);
624 parse_text(p, os, FLAG_END, outer, context);
625 context.check_end_layout(os);
626 if (parent_context.deeper_paragraph) {
627 // We must suppress the "end deeper" because we
628 // suppressed the "begin deeper" above.
629 context.need_end_deeper = false;
631 context.check_end_deeper(os);
632 parent_context.new_paragraph(os);
635 else if (name == "appendix") {
636 // This is no good latex style, but it works and is used in some documents...
637 parent_context.check_end_layout(os);
638 Context context(true, parent_context.textclass, parent_context.layout,
639 parent_context.layout);
640 context.check_layout(os);
641 os << "\\start_of_appendix\n";
642 parse_text(p, os, FLAG_END, outer, context);
643 context.check_end_layout(os);
646 else if (name == "comment") {
647 parent_context.check_layout(os);
648 begin_inset(os, "Note Comment\n");
649 os << "status open\n";
650 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
654 else if (name == "lyxgreyedout") {
655 parent_context.check_layout(os);
656 begin_inset(os, "Note Greyedout\n");
657 os << "status open\n";
658 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
662 else if (name == "tabbing") {
663 // We need to remember that we have to handle '\=' specially
664 handle_ert(os, "\\begin{" + name + "}", parent_context);
665 parse_text_snippet(p, os, FLAG_END | FLAG_TABBING, outer, parent_context);
666 handle_ert(os, "\\end{" + name + "}", parent_context);
670 handle_ert(os, "\\begin{" + name + "}", parent_context);
671 parse_text_snippet(p, os, FLAG_END, outer, parent_context);
672 handle_ert(os, "\\end{" + name + "}", parent_context);
675 active_environments.pop_back();
680 /// parses a comment and outputs it to \p os.
681 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
683 BOOST_ASSERT(t.cat() == catComment);
684 context.check_layout(os);
685 if (!t.cs().empty()) {
686 handle_comment(os, '%' + t.cs(), context);
687 if (p.next_token().cat() == catNewline) {
688 // A newline after a comment line starts a new
690 if(!context.atParagraphStart()) {
691 // Only start a new paragraph if not already
692 // done (we might get called recursively)
693 context.new_paragraph(os);
695 eat_whitespace(p, os, context, true);
705 * Reads spaces and comments until the first non-space, non-comment token.
706 * New paragraphs (double newlines or \\par) are handled like simple spaces
707 * if \p eatParagraph is true.
708 * Spaces are skipped, but comments are written to \p os.
710 void eat_whitespace(Parser & p, ostream & os, Context & context,
714 Token const & t = p.get_token();
715 if (t.cat() == catComment)
716 parse_comment(p, os, t, context);
717 else if ((! eatParagraph && p.isParagraph()) ||
718 (t.cat() != catSpace && t.cat() != catNewline)) {
725 } // anonymous namespace
728 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
731 LyXLayout_ptr newlayout;
732 // Store the latest bibliographystyle (needed for bibtex inset)
733 string bibliographystyle;
735 Token const & t = p.get_token();
738 cerr << "t: " << t << " flags: " << flags << "\n";
741 if (flags & FLAG_ITEM) {
742 if (t.cat() == catSpace)
746 if (t.cat() == catBegin) {
747 // skip the brace and collect everything to the next matching
749 flags |= FLAG_BRACE_LAST;
753 // handle only this single token, leave the loop if done
757 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
763 if (t.cat() == catMath) {
764 // we are inside some text mode thingy, so opening new math is allowed
765 context.check_layout(os);
766 begin_inset(os, "Formula ");
767 Token const & n = p.get_token();
768 if (n.cat() == catMath && outer) {
769 // TeX's $$...$$ syntax for displayed math
771 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
773 p.get_token(); // skip the second '$' token
775 // simple $...$ stuff
778 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
784 else if (t.cat() == catSuper || t.cat() == catSub)
785 cerr << "catcode " << t << " illegal in text mode\n";
787 // Basic support for english quotes. This should be
788 // extended to other quotes, but is not so easy (a
789 // left english quote is the same as a right german
791 else if (t.asInput() == "`"
792 && p.next_token().asInput() == "`") {
793 context.check_layout(os);
794 begin_inset(os, "Quotes ");
800 else if (t.asInput() == "'"
801 && p.next_token().asInput() == "'") {
802 context.check_layout(os);
803 begin_inset(os, "Quotes ");
810 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
811 check_space(p, os, context);
813 else if (t.cat() == catLetter ||
814 t.cat() == catOther ||
815 t.cat() == catAlign ||
816 t.cat() == catParameter) {
817 context.check_layout(os);
821 else if (p.isParagraph()) {
822 context.new_paragraph(os);
823 eat_whitespace(p, os, context, true);
826 else if (t.cat() == catActive) {
827 context.check_layout(os);
828 if (t.character() == '~') {
829 if (context.layout->free_spacing)
832 os << "\\InsetSpace ~\n";
837 else if (t.cat() == catBegin) {
838 // special handling of size changes
839 context.check_layout(os);
840 bool const is_size = is_known(p.next_token().cs(), known_sizes);
841 Token const prev = p.prev_token();
842 string const s = parse_text(p, FLAG_BRACE_LAST, outer, context);
843 if (s.empty() && (p.next_token().character() == '`' ||
844 (prev.character() == '-' && p.next_token().character())))
845 ; // ignore it in {}`` or -{}-
846 else if (is_size || s == "[" || s == "]" || s == "*")
849 handle_ert(os, "{", context, false);
850 // s will end the current layout and begin a new one if necessary
852 handle_ert(os, "}", context);
856 else if (t.cat() == catEnd) {
857 if (flags & FLAG_BRACE_LAST) {
860 cerr << "stray '}' in text\n";
861 handle_ert(os, "}", context);
864 else if (t.cat() == catComment)
865 parse_comment(p, os, t, context);
871 else if (t.cs() == "(") {
872 context.check_layout(os);
873 begin_inset(os, "Formula");
875 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
880 else if (t.cs() == "[") {
881 context.check_layout(os);
882 begin_inset(os, "Formula");
884 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
889 else if (t.cs() == "begin")
890 parse_environment(p, os, outer, context);
892 else if (t.cs() == "end") {
893 if (flags & FLAG_END) {
894 // eat environment name
895 string const name = p.getArg('{', '}');
896 if (name != active_environment())
897 cerr << "\\end{" + name + "} does not match \\begin{"
898 + active_environment() + "}\n";
901 p.error("found 'end' unexpectedly");
904 else if (t.cs() == "item") {
908 if (p.next_token().character() == '[') {
909 p.get_token(); // eat '['
910 Context newcontext(false, context.textclass);
911 s = parse_text(p, FLAG_BRACK_LAST, outer, newcontext);
915 context.check_layout(os);
917 if (context.layout->labeltype != LABEL_MANUAL) {
918 // lyx does not support \item[\mybullet] in itemize environments
919 handle_ert(os, "[", context);
921 handle_ert(os, "]", context);
922 } else if (!s.empty()) {
923 // The space is needed to separate the item from the rest of the sentence.
925 eat_whitespace(p, os, context, false);
930 else if (t.cs() == "bibitem") {
932 context.check_layout(os);
935 os << '{' << p.verbatim_item() << '}' << "\n";
938 else if (t.cs() == "def") {
939 context.check_layout(os);
940 eat_whitespace(p, os, context, false);
941 string name = p.get_token().cs();
942 while (p.next_token().cat() != catBegin)
943 name += p.get_token().asString();
944 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
947 else if (t.cs() == "noindent") {
949 context.add_extra_stuff("\\noindent ");
952 else if (t.cs() == "appendix") {
954 context.add_extra_stuff("\\start_of_appendix ");
957 // Must attempt to parse "Section*" before "Section".
958 else if ((p.next_token().asInput() == "*") &&
959 // The single '=' is meant here.
960 (newlayout = findLayout(context.textclass,
961 t.cs() + '*')).get() &&
962 newlayout->isCommand()) {
964 output_command_layout(os, p, outer, context, newlayout);
968 // The single '=' is meant here.
969 else if ((newlayout = findLayout(context.textclass, t.cs())).get() &&
970 newlayout->isCommand()) {
971 output_command_layout(os, p, outer, context, newlayout);
975 else if (t.cs() == "includegraphics") {
976 map<string, string> opts = split_map(p.getArg('[', ']'));
977 string name = subst(p.verbatim_item(), "\\lyxdot ", ".");
979 context.check_layout(os);
980 begin_inset(os, "Graphics ");
981 os << "\n\tfilename " << name << '\n';
982 if (opts.find("width") != opts.end())
984 << translate_len(opts["width"]) << '\n';
985 if (opts.find("height") != opts.end())
987 << translate_len(opts["height"]) << '\n';
988 if (opts.find("scale") != opts.end()) {
989 istringstream iss(opts["scale"]);
993 os << "\tscale " << val << '\n';
995 if (opts.find("angle") != opts.end())
996 os << "\trotateAngle "
997 << opts["angle"] << '\n';
998 if (opts.find("origin") != opts.end()) {
1000 string const opt = opts["origin"];
1001 if (opt.find('l') != string::npos) ss << "left";
1002 if (opt.find('r') != string::npos) ss << "right";
1003 if (opt.find('c') != string::npos) ss << "center";
1004 if (opt.find('t') != string::npos) ss << "Top";
1005 if (opt.find('b') != string::npos) ss << "Bottom";
1006 if (opt.find('B') != string::npos) ss << "Baseline";
1007 if (!ss.str().empty())
1008 os << "\trotateOrigin " << ss.str() << '\n';
1010 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1012 if (opts.find("keepaspectratio") != opts.end())
1013 os << "\tkeepAspectRatio\n";
1014 if (opts.find("clip") != opts.end())
1016 if (opts.find("draft") != opts.end())
1018 if (opts.find("bb") != opts.end())
1019 os << "\tBoundingBox "
1020 << opts["bb"] << '\n';
1021 int numberOfbbOptions = 0;
1022 if (opts.find("bbllx") != opts.end())
1023 numberOfbbOptions++;
1024 if (opts.find("bblly") != opts.end())
1025 numberOfbbOptions++;
1026 if (opts.find("bburx") != opts.end())
1027 numberOfbbOptions++;
1028 if (opts.find("bbury") != opts.end())
1029 numberOfbbOptions++;
1030 if (numberOfbbOptions == 4)
1031 os << "\tBoundingBox "
1032 << opts["bbllx"] << opts["bblly"]
1033 << opts["bburx"] << opts["bbury"] << '\n';
1034 else if (numberOfbbOptions > 0)
1035 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1036 numberOfbbOptions = 0;
1037 if (opts.find("natwidth") != opts.end())
1038 numberOfbbOptions++;
1039 if (opts.find("natheight") != opts.end())
1040 numberOfbbOptions++;
1041 if (numberOfbbOptions == 2)
1042 os << "\tBoundingBox 0bp 0bp "
1043 << opts["natwidth"] << opts["natheight"] << '\n';
1044 else if (numberOfbbOptions > 0)
1045 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1046 ostringstream special;
1047 if (opts.find("hiresbb") != opts.end())
1048 special << "hiresbb,";
1049 if (opts.find("trim") != opts.end())
1051 if (opts.find("viewport") != opts.end())
1052 special << "viewport=" << opts["viewport"] << ',';
1053 if (opts.find("totalheight") != opts.end())
1054 special << "totalheight=" << opts["totalheight"] << ',';
1055 if (opts.find("type") != opts.end())
1056 special << "type=" << opts["type"] << ',';
1057 if (opts.find("ext") != opts.end())
1058 special << "ext=" << opts["ext"] << ',';
1059 if (opts.find("read") != opts.end())
1060 special << "read=" << opts["read"] << ',';
1061 if (opts.find("command") != opts.end())
1062 special << "command=" << opts["command"] << ',';
1063 string s_special = special.str();
1064 if (!s_special.empty()) {
1065 // We had special arguments. Remove the trailing ','.
1066 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1068 // TODO: Handle the unknown settings better.
1069 // Warn about invalid options.
1070 // Check whether some option was given twice.
1074 else if (t.cs() == "footnote") {
1076 context.check_layout(os);
1077 begin_inset(os, "Foot\n");
1078 os << "status collapsed\n\n";
1079 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1083 else if (t.cs() == "marginpar") {
1085 context.check_layout(os);
1086 begin_inset(os, "Marginal\n");
1087 os << "status collapsed\n\n";
1088 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1092 else if (t.cs() == "ensuremath") {
1094 context.check_layout(os);
1095 Context newcontext(false, context.textclass);
1096 string s = parse_text(p, FLAG_ITEM, false, newcontext);
1097 if (s == "±" || s == "³" || s == "²" || s == "µ")
1100 handle_ert(os, "\\ensuremath{" + s + "}",
1104 else if (t.cs() == "hfill") {
1105 context.check_layout(os);
1106 os << "\n\\hfill \n";
1111 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1113 skip_braces(p); // swallow this
1116 else if (t.cs() == "tableofcontents") {
1118 context.check_layout(os);
1119 begin_inset(os, "LatexCommand \\tableofcontents\n");
1121 skip_braces(p); // swallow this
1124 else if (t.cs() == "listoffigures") {
1126 context.check_layout(os);
1127 begin_inset(os, "FloatList figure\n");
1129 skip_braces(p); // swallow this
1132 else if (t.cs() == "listoftables") {
1134 context.check_layout(os);
1135 begin_inset(os, "FloatList table\n");
1137 skip_braces(p); // swallow this
1140 else if (t.cs() == "listof") {
1141 p.skip_spaces(true);
1142 string const name = p.get_token().asString();
1143 if (context.textclass.floats().typeExist(name)) {
1144 context.check_layout(os);
1145 begin_inset(os, "FloatList ");
1148 p.get_token(); // swallow second arg
1150 handle_ert(os, "\\listof{" + name + "}", context);
1153 else if (t.cs() == "textrm") {
1154 context.check_layout(os);
1155 os << "\n\\family roman \n";
1156 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1157 os << "\n\\family default \n";
1160 else if (t.cs() == "textsf") {
1161 context.check_layout(os);
1162 os << "\n\\family sans \n";
1163 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1164 os << "\n\\family default \n";
1167 else if (t.cs() == "textsl") {
1168 context.check_layout(os);
1169 os << "\n\\shape slanted \n";
1170 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1171 os << "\n\\shape default \n";
1174 else if (t.cs() == "texttt") {
1175 context.check_layout(os);
1176 os << "\n\\family typewriter \n";
1177 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1178 os << "\n\\family default \n";
1181 else if (t.cs() == "textit") {
1182 context.check_layout(os);
1183 os << "\n\\shape italic \n";
1184 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1185 os << "\n\\shape default \n";
1188 else if (t.cs() == "textsc") {
1189 context.check_layout(os);
1190 os << "\n\\noun on \n";
1191 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1192 os << "\n\\noun default \n";
1195 else if (t.cs() == "textbf") {
1196 context.check_layout(os);
1197 os << "\n\\series bold \n";
1198 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1199 os << "\n\\series default \n";
1202 else if (t.cs() == "underbar") {
1203 context.check_layout(os);
1204 os << "\n\\bar under \n";
1205 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1206 os << "\n\\bar default \n";
1209 else if (t.cs() == "emph" || t.cs() == "noun") {
1210 context.check_layout(os);
1211 os << "\n\\" << t.cs() << " on \n";
1212 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1213 os << "\n\\" << t.cs() << " default \n";
1216 else if (is_known(t.cs(), known_latex_commands)) {
1217 context.check_layout(os);
1218 begin_inset(os, "LatexCommand ");
1219 os << '\\' << t.cs();
1222 os << '{' << p.verbatim_item() << "}\n";
1226 else if (is_known(t.cs(), known_quotes)) {
1227 char const ** where = is_known(t.cs(), known_quotes);
1228 context.check_layout(os);
1229 begin_inset(os, "Quotes ");
1230 os << known_coded_quotes[where - known_quotes];
1232 // LyX adds {} after the quote, so we have to eat
1233 // spaces here if there are any before a possible
1235 eat_whitespace(p, os, context, false);
1239 else if (is_known(t.cs(), known_sizes)) {
1240 char const ** where = is_known(t.cs(), known_sizes);
1241 context.check_layout(os);
1242 os << "\n\\size " << known_coded_sizes[where - known_sizes] << "\n";
1243 eat_whitespace(p, os, context, false);
1246 else if (t.cs() == "LyX" || t.cs() == "TeX"
1247 || t.cs() == "LaTeX") {
1248 context.check_layout(os);
1250 skip_braces(p); // eat {}
1253 else if (t.cs() == "LaTeXe") {
1254 context.check_layout(os);
1256 skip_braces(p); // eat {}
1259 else if (t.cs() == "ldots") {
1260 context.check_layout(os);
1262 os << "\\SpecialChar \\ldots{}\n";
1265 else if (t.cs() == "lyxarrow") {
1266 context.check_layout(os);
1267 os << "\\SpecialChar \\menuseparator\n";
1271 else if (t.cs() == "textcompwordmark") {
1272 context.check_layout(os);
1273 os << "\\SpecialChar \\textcompwordmark{}\n";
1277 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
1278 context.check_layout(os);
1279 os << "\\SpecialChar \\@.\n";
1283 else if (t.cs() == "-") {
1284 context.check_layout(os);
1285 os << "\\SpecialChar \\-\n";
1288 else if (t.cs() == "textasciitilde") {
1289 context.check_layout(os);
1294 else if (t.cs() == "textasciicircum") {
1295 context.check_layout(os);
1300 else if (t.cs() == "textbackslash") {
1301 context.check_layout(os);
1302 os << "\n\\backslash \n";
1306 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
1307 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
1309 context.check_layout(os);
1313 else if (t.cs() == "char") {
1314 context.check_layout(os);
1315 if (p.next_token().character() == '`') {
1317 if (p.next_token().cs() == "\"") {
1322 handle_ert(os, "\\char`", context);
1325 handle_ert(os, "\\char", context);
1329 else if (t.cs() == "\"") {
1330 context.check_layout(os);
1331 string const name = p.verbatim_item();
1332 if (name == "a") os << 'ä';
1333 else if (name == "o") os << 'ö';
1334 else if (name == "u") os << 'ü';
1335 else if (name == "A") os << 'Ä';
1336 else if (name == "O") os << 'Ö';
1337 else if (name == "U") os << 'Ü';
1338 else handle_ert(os, "\"{" + name + "}", context);
1341 // Problem: \= creates a tabstop inside the tabbing environment
1342 // and else an accent. In the latter case we really would want
1343 // \={o} instead of \= o.
1344 else if (t.cs() == "=" && (flags & FLAG_TABBING))
1345 handle_ert(os, t.asInput(), context);
1347 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^" || t.cs() == "'"
1348 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
1349 // we need the trim as the LyX parser chokes on such spaces
1350 context.check_layout(os);
1351 os << "\n\\i \\" << t.cs() << "{"
1352 << trim(parse_text(p, FLAG_ITEM, outer, context), " ") << "}\n";
1355 else if (t.cs() == "ss") {
1356 context.check_layout(os);
1360 else if (t.cs() == "i" || t.cs() == "j") {
1361 context.check_layout(os);
1362 os << "\\" << t.cs() << ' ';
1365 else if (t.cs() == "\\") {
1366 context.check_layout(os);
1367 string const next = p.next_token().asInput();
1369 handle_ert(os, "\\\\" + p.getOpt(), context);
1370 else if (next == "*") {
1372 handle_ert(os, "\\\\*" + p.getOpt(), context);
1375 os << "\n\\newline \n";
1379 else if (t.cs() == "input" || t.cs() == "include"
1380 || t.cs() == "verbatiminput") {
1381 string name = '\\' + t.cs();
1382 if (t.cs() == "verbatiminput"
1383 && p.next_token().asInput() == "*")
1384 name += p.get_token().asInput();
1385 context.check_layout(os);
1386 begin_inset(os, "Include ");
1387 string filename(p.getArg('{', '}'));
1388 string lyxname(lyx::support::ChangeExtension(filename, ".lyx"));
1389 if (tex2lyx(filename, lyxname)) {
1390 os << name << '{' << lyxname << "}\n";
1392 os << name << '{' << filename << "}\n";
1394 os << "preview false\n";
1398 else if (t.cs() == "fancyhead") {
1399 context.check_layout(os);
1401 ss << "\\fancyhead";
1403 ss << '{' << p.verbatim_item() << "}\n";
1404 handle_ert(os, ss.str(), context);
1407 else if (t.cs() == "bibliographystyle") {
1408 // store new bibliographystyle
1409 bibliographystyle = p.verbatim_item();
1410 // output new bibliographystyle.
1411 // This is only necessary if used in some other macro than \bibliography.
1412 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
1415 else if (t.cs() == "bibliography") {
1416 context.check_layout(os);
1417 begin_inset(os, "LatexCommand ");
1419 // Do we have a bibliographystyle set?
1420 if (!bibliographystyle.empty()) {
1421 os << '[' << bibliographystyle << ']';
1423 os << '{' << p.verbatim_item() << "}\n";
1427 else if (t.cs() == "parbox")
1428 parse_box(p, os, FLAG_ITEM, outer, context, true);
1430 else if (t.cs() == "smallskip" ||
1431 t.cs() == "medskip" ||
1432 t.cs() == "bigskip" ||
1433 t.cs() == "vfill") {
1434 context.check_layout(os);
1435 begin_inset(os, "VSpace ");
1441 else if (t.cs() == "vspace") {
1442 bool starred = false;
1443 if (p.next_token().asInput() == "*") {
1447 string const length = p.verbatim_item();
1450 bool valid = splitLatexLength(length, valstring, unit);
1451 bool known_vspace = false;
1452 bool known_unit = false;
1455 istringstream iss(valstring);
1458 if (unit == "\\smallskipamount") {
1460 known_vspace = true;
1461 } else if (unit == "\\medskipamount") {
1463 known_vspace = true;
1464 } else if (unit == "\\bigskipamount") {
1466 known_vspace = true;
1467 } else if (unit == "\\fill") {
1469 known_vspace = true;
1472 if (!known_vspace) {
1473 switch (unitFromString(unit)) {
1494 if (known_unit || known_vspace) {
1495 // Literal length or known variable
1496 context.check_layout(os);
1497 begin_inset(os, "VSpace ");
1505 // LyX can't handle other length variables in Inset VSpace
1506 string name = t.asInput();
1511 handle_ert(os, name + '{' + unit + '}', context);
1512 else if (value == -1.0)
1513 handle_ert(os, name + "{-" + unit + '}', context);
1515 handle_ert(os, name + '{' + valstring + unit + '}', context);
1517 handle_ert(os, name + '{' + length + '}', context);
1522 //cerr << "#: " << t << " mode: " << mode << endl;
1523 // heuristic: read up to next non-nested space
1525 string s = t.asInput();
1526 string z = p.verbatim_item();
1527 while (p.good() && z != " " && z.size()) {
1528 //cerr << "read: " << z << endl;
1530 z = p.verbatim_item();
1532 cerr << "found ERT: " << s << endl;
1533 handle_ert(os, s + ' ', context);
1535 string name = t.asInput();
1536 if (p.next_token().asInput() == "*") {
1537 // Starred commands like \vspace*{}
1538 p.get_token(); // Eat '*'
1541 if (! parse_command(name, p, os, outer, context))
1542 handle_ert(os, name, context);
1545 if (flags & FLAG_LEAVE) {
1546 flags &= ~FLAG_LEAVE;