3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jean-Marc Lasgouttes
9 * Full author contact details are available in file CREDITS.
18 #include "FloatList.h"
19 #include "lengthcommon.h"
20 #include "support/lstrings.h"
21 #include "support/convert.h"
22 #include "support/filetools.h"
24 #include <boost/filesystem/operations.hpp>
25 #include <boost/tuple/tuple.hpp>
35 using support::addExtension;
36 using support::changeExtension;
37 using support::FileName;
38 using support::makeAbsPath;
39 using support::makeRelPath;
41 using support::suffixIs;
42 using support::contains;
50 using std::ostringstream;
51 using std::istringstream;
55 namespace fs = boost::filesystem;
58 void parse_text_in_inset(Parser & p, ostream & os, unsigned flags, bool outer,
59 Context const & context)
61 Context newcontext(true, context.textclass);
62 newcontext.font = context.font;
63 parse_text(p, os, flags, outer, newcontext);
64 newcontext.check_end_layout(os);
70 /// parses a paragraph snippet, useful for example for \\emph{...}
71 void parse_text_snippet(Parser & p, ostream & os, unsigned flags, bool outer,
74 Context newcontext(context);
75 // Don't inherit the extra stuff
76 newcontext.extra_stuff.clear();
77 parse_text(p, os, flags, outer, newcontext);
78 // Make sure that we don't create invalid .lyx files
79 context.need_layout = newcontext.need_layout;
80 context.need_end_layout = newcontext.need_end_layout;
85 * Thin wrapper around parse_text_snippet() using a string.
87 * We completely ignore \c context.need_layout and \c context.need_end_layout,
88 * because our return value is not used directly (otherwise the stream version
89 * of parse_text_snippet() could be used). That means that the caller needs
90 * to do layout management manually.
91 * This is intended to parse text that does not create any layout changes.
93 string parse_text_snippet(Parser & p, unsigned flags, const bool outer,
96 Context newcontext(context);
97 newcontext.need_layout = false;
98 newcontext.need_end_layout = false;
99 newcontext.new_layout_allowed = false;
100 // Avoid warning by Context::~Context()
101 newcontext.extra_stuff.clear();
103 parse_text_snippet(p, os, flags, outer, newcontext);
108 char const * const known_latex_commands[] = { "ref", "cite", "label", "index",
109 "printindex", "pageref", "url", "vref", "vpageref", "prettyref", "eqref", 0 };
113 * We can't put these into known_latex_commands because the argument order
114 * is reversed in lyx if there are 2 arguments.
115 * The starred forms are also known.
117 char const * const known_natbib_commands[] = { "cite", "citet", "citep",
118 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
119 "citefullauthor", "Citet", "Citep", "Citealt", "Citealp", "Citeauthor", 0 };
123 * We can't put these into known_latex_commands because the argument order
124 * is reversed in lyx if there are 2 arguments.
125 * No starred form other than "cite*" known.
127 char const * const known_jurabib_commands[] = { "cite", "citet", "citep",
128 "citealt", "citealp", "citeauthor", "citeyear", "citeyearpar",
129 // jurabib commands not (yet) supported by LyX:
131 // "footcite", "footcitet", "footcitep", "footcitealt", "footcitealp",
132 // "footciteauthor", "footciteyear", "footciteyearpar",
133 "citefield", "citetitle", "cite*", 0 };
135 /// LaTeX names for quotes
136 char const * const known_quotes[] = { "glqq", "grqq", "quotedblbase",
137 "textquotedblleft", "quotesinglbase", "guilsinglleft", "guilsinglright", 0};
139 /// the same as known_quotes with .lyx names
140 char const * const known_coded_quotes[] = { "gld", "grd", "gld",
141 "grd", "gls", "fls", "frs", 0};
143 /// LaTeX names for font sizes
144 char const * const known_sizes[] = { "tiny", "scriptsize", "footnotesize",
145 "small", "normalsize", "large", "Large", "LARGE", "huge", "Huge", 0};
147 /// the same as known_sizes with .lyx names
148 char const * const known_coded_sizes[] = { "tiny", "scriptsize", "footnotesize",
149 "small", "normal", "large", "larger", "largest", "huge", "giant", 0};
151 /// LaTeX 2.09 names for font families
152 char const * const known_old_font_families[] = { "rm", "sf", "tt", 0};
154 /// LaTeX names for font families
155 char const * const known_font_families[] = { "rmfamily", "sffamily",
158 /// the same as known_old_font_families and known_font_families with .lyx names
159 char const * const known_coded_font_families[] = { "roman", "sans",
162 /// LaTeX 2.09 names for font series
163 char const * const known_old_font_series[] = { "bf", 0};
165 /// LaTeX names for font series
166 char const * const known_font_series[] = { "bfseries", "mdseries", 0};
168 /// the same as known_old_font_series and known_font_series with .lyx names
169 char const * const known_coded_font_series[] = { "bold", "medium", 0};
171 /// LaTeX 2.09 names for font shapes
172 char const * const known_old_font_shapes[] = { "it", "sl", "sc", 0};
174 /// LaTeX names for font shapes
175 char const * const known_font_shapes[] = { "itshape", "slshape", "scshape",
178 /// the same as known_old_font_shapes and known_font_shapes with .lyx names
179 char const * const known_coded_font_shapes[] = { "italic", "slanted",
180 "smallcaps", "up", 0};
183 * Graphics file extensions known by the dvips driver of the graphics package.
184 * These extensions are used to complete the filename of an included
185 * graphics file if it does not contain an extension.
186 * The order must be the same that latex uses to find a file, because we
187 * will use the first extension that matches.
188 * This is only an approximation for the common cases. If we would want to
189 * do it right in all cases, we would need to know which graphics driver is
190 * used and know the extensions of every driver of the graphics package.
192 char const * const known_dvips_graphics_formats[] = {"eps", "ps", "eps.gz",
193 "ps.gz", "eps.Z", "ps.Z", 0};
196 * Graphics file extensions known by the pdftex driver of the graphics package.
197 * \sa known_dvips_graphics_formats
199 char const * const known_pdftex_graphics_formats[] = {"png", "pdf", "jpg",
203 * Known file extensions for TeX files as used by \\include.
205 char const * const known_tex_extensions[] = {"tex", 0};
207 /// spaces known by InsetSpace
208 char const * const known_spaces[] = { " ", "space", ",", "thinspace", "quad",
209 "qquad", "enspace", "enskip", "negthinspace", 0};
211 /// the same as known_spaces with .lyx names
212 char const * const known_coded_spaces[] = { "space{}", "space{}",
213 "thinspace{}", "thinspace{}", "quad{}", "qquad{}", "enspace{}", "enskip{}",
214 "negthinspace{}", 0};
217 /// splits "x=z, y=b" into a map
218 map<string, string> split_map(string const & s)
220 map<string, string> res;
223 for (size_t i = 0; i < v.size(); ++i) {
224 size_t const pos = v[i].find('=');
225 string const index = v[i].substr(0, pos);
226 string const value = v[i].substr(pos + 1, string::npos);
227 res[trim(index)] = trim(value);
234 * Split a LaTeX length into value and unit.
235 * The latter can be a real unit like "pt", or a latex length variable
236 * like "\textwidth". The unit may contain additional stuff like glue
237 * lengths, but we don't care, because such lengths are ERT anyway.
238 * \returns true if \p value and \p unit are valid.
240 bool splitLatexLength(string const & len, string & value, string & unit)
244 const string::size_type i = len.find_first_not_of(" -+0123456789.,");
245 //'4,5' is a valid LaTeX length number. Change it to '4.5'
246 string const length = subst(len, ',', '.');
247 if (i == string::npos)
250 if (len[0] == '\\') {
251 // We had something like \textwidth without a factor
257 value = trim(string(length, 0, i));
261 // 'cM' is a valid LaTeX length unit. Change it to 'cm'
262 if (contains(len, '\\'))
263 unit = trim(string(len, i));
265 unit = lyx::support::lowercase(trim(string(len, i)));
270 /// A simple function to translate a latex length to something lyx can
271 /// understand. Not perfect, but rather best-effort.
272 bool translate_len(string const & length, string & valstring, string & unit)
274 if (!splitLatexLength(length, valstring, unit))
276 // LyX uses percent values
278 istringstream iss(valstring);
283 string const percentval = oss.str();
285 if (unit.empty() || unit[0] != '\\')
287 string::size_type const i = unit.find(' ');
288 string const endlen = (i == string::npos) ? string() : string(unit, i);
289 if (unit == "\\textwidth") {
290 valstring = percentval;
291 unit = "text%" + endlen;
292 } else if (unit == "\\columnwidth") {
293 valstring = percentval;
294 unit = "col%" + endlen;
295 } else if (unit == "\\paperwidth") {
296 valstring = percentval;
297 unit = "page%" + endlen;
298 } else if (unit == "\\linewidth") {
299 valstring = percentval;
300 unit = "line%" + endlen;
301 } else if (unit == "\\paperheight") {
302 valstring = percentval;
303 unit = "pheight%" + endlen;
304 } else if (unit == "\\textheight") {
305 valstring = percentval;
306 unit = "theight%" + endlen;
314 string translate_len(string const & length)
318 if (translate_len(length, value, unit))
320 // If the input is invalid, return what we have.
328 * Translates a LaTeX length into \p value, \p unit and
329 * \p special parts suitable for a box inset.
330 * The difference from translate_len() is that a box inset knows about
331 * some special "units" that are stored in \p special.
333 void translate_box_len(string const & length, string & value, string & unit, string & special)
335 if (translate_len(length, value, unit)) {
336 if (unit == "\\height" || unit == "\\depth" ||
337 unit == "\\totalheight" || unit == "\\width") {
338 special = unit.substr(1);
339 // The unit is not used, but LyX requires a dummy setting
352 * Find a file with basename \p name in path \p path and an extension
355 string find_file(string const & name, string const & path,
356 char const * const * extensions)
358 // FIXME UNICODE encoding of name and path may be wrong (makeAbsPath
360 for (char const * const * what = extensions; *what; ++what) {
361 string const trial = addExtension(name, *what);
362 if (fs::exists(makeAbsPath(trial, path).toFilesystemEncoding()))
369 void begin_inset(ostream & os, string const & name)
371 os << "\n\\begin_inset " << name;
375 void end_inset(ostream & os)
377 os << "\n\\end_inset\n\n";
381 void skip_braces(Parser & p)
383 if (p.next_token().cat() != catBegin)
386 if (p.next_token().cat() == catEnd) {
394 void handle_ert(ostream & os, string const & s, Context & context)
396 // We must have a valid layout before outputting the ERT inset.
397 context.check_layout(os);
398 Context newcontext(true, context.textclass);
399 begin_inset(os, "ERT");
400 os << "\nstatus collapsed\n";
401 newcontext.check_layout(os);
402 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
404 os << "\n\\backslash\n";
405 else if (*it == '\n') {
406 newcontext.new_paragraph(os);
407 newcontext.check_layout(os);
411 newcontext.check_end_layout(os);
416 void handle_comment(ostream & os, string const & s, Context & context)
418 // TODO: Handle this better
419 Context newcontext(true, context.textclass);
420 begin_inset(os, "ERT");
421 os << "\nstatus collapsed\n";
422 newcontext.check_layout(os);
423 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
425 os << "\n\\backslash\n";
429 // make sure that our comment is the last thing on the line
430 newcontext.new_paragraph(os);
431 newcontext.check_layout(os);
432 newcontext.check_end_layout(os);
437 class isLayout : public std::unary_function<LyXLayout_ptr, bool> {
439 isLayout(string const name) : name_(name) {}
440 bool operator()(LyXLayout_ptr const & ptr) const {
441 return ptr->latexname() == name_;
448 LyXLayout_ptr findLayout(LyXTextClass const & textclass,
451 LyXTextClass::const_iterator beg = textclass.begin();
452 LyXTextClass::const_iterator end = textclass.end();
454 LyXTextClass::const_iterator
455 it = std::find_if(beg, end, isLayout(name));
457 return (it == end) ? LyXLayout_ptr() : *it;
461 void eat_whitespace(Parser &, ostream &, Context &, bool);
464 void output_command_layout(ostream & os, Parser & p, bool outer,
465 Context & parent_context,
466 LyXLayout_ptr newlayout)
468 parent_context.check_end_layout(os);
469 Context context(true, parent_context.textclass, newlayout,
470 parent_context.layout, parent_context.font);
471 if (parent_context.deeper_paragraph) {
472 // We are beginning a nested environment after a
473 // deeper paragraph inside the outer list environment.
474 // Therefore we don't need to output a "begin deeper".
475 context.need_end_deeper = true;
477 context.check_deeper(os);
478 context.check_layout(os);
479 if (context.layout->optionalargs > 0) {
480 eat_whitespace(p, os, context, false);
481 if (p.next_token().character() == '[') {
482 p.get_token(); // eat '['
483 begin_inset(os, "OptArg\n");
484 os << "status collapsed\n\n";
485 parse_text_in_inset(p, os, FLAG_BRACK_LAST, outer, context);
487 eat_whitespace(p, os, context, false);
490 parse_text(p, os, FLAG_ITEM, outer, context);
491 context.check_end_layout(os);
492 if (parent_context.deeper_paragraph) {
493 // We must suppress the "end deeper" because we
494 // suppressed the "begin deeper" above.
495 context.need_end_deeper = false;
497 context.check_end_deeper(os);
498 // We don't need really a new paragraph, but
499 // we must make sure that the next item gets a \begin_layout.
500 parent_context.new_paragraph(os);
505 * Output a space if necessary.
506 * This function gets called for every whitespace token.
508 * We have three cases here:
509 * 1. A space must be suppressed. Example: The lyxcode case below
510 * 2. A space may be suppressed. Example: Spaces before "\par"
511 * 3. A space must not be suppressed. Example: A space between two words
513 * We currently handle only 1. and 3 and from 2. only the case of
514 * spaces before newlines as a side effect.
516 * 2. could be used to suppress as many spaces as possible. This has two effects:
517 * - Reimporting LyX generated LaTeX files changes almost no whitespace
518 * - Superflous whitespace from non LyX generated LaTeX files is removed.
519 * The drawback is that the logic inside the function becomes
520 * complicated, and that is the reason why it is not implemented.
522 void check_space(Parser const & p, ostream & os, Context & context)
524 Token const next = p.next_token();
525 Token const curr = p.curr_token();
526 // A space before a single newline and vice versa must be ignored
527 // LyX emits a newline before \end{lyxcode}.
528 // This newline must be ignored,
529 // otherwise LyX will add an additional protected space.
530 if (next.cat() == catSpace ||
531 next.cat() == catNewline ||
532 (next.cs() == "end" && context.layout->free_spacing && curr.cat() == catNewline)) {
535 context.check_layout(os);
541 * Parse all arguments of \p command
543 void parse_arguments(string const & command,
544 vector<ArgumentType> const & template_arguments,
545 Parser & p, ostream & os, bool outer, Context & context)
547 string ert = command;
548 size_t no_arguments = template_arguments.size();
549 for (size_t i = 0; i < no_arguments; ++i) {
550 switch (template_arguments[i]) {
552 // This argument contains regular LaTeX
553 handle_ert(os, ert + '{', context);
554 eat_whitespace(p, os, context, false);
555 parse_text(p, os, FLAG_ITEM, outer, context);
559 // This argument may contain special characters
560 ert += '{' + p.verbatim_item() + '}';
567 handle_ert(os, ert, context);
572 * Check whether \p command is a known command. If yes,
573 * handle the command with all arguments.
574 * \return true if the command was parsed, false otherwise.
576 bool parse_command(string const & command, Parser & p, ostream & os,
577 bool outer, Context & context)
579 if (known_commands.find(command) != known_commands.end()) {
580 parse_arguments(command, known_commands[command], p, os,
588 /// Parses a minipage or parbox
589 void parse_box(Parser & p, ostream & os, unsigned flags, bool outer,
590 Context & parent_context, bool use_parbox)
594 string height_value = "0";
595 string height_unit = "pt";
596 string height_special = "none";
598 if (p.next_token().asInput() == "[") {
599 position = p.getArg('[', ']');
600 if (position != "t" && position != "c" && position != "b") {
602 cerr << "invalid position for minipage/parbox" << endl;
604 if (p.next_token().asInput() == "[") {
605 latex_height = p.getArg('[', ']');
606 translate_box_len(latex_height, height_value, height_unit, height_special);
608 if (p.next_token().asInput() == "[") {
609 inner_pos = p.getArg('[', ']');
610 if (inner_pos != "c" && inner_pos != "t" &&
611 inner_pos != "b" && inner_pos != "s") {
612 inner_pos = position;
613 cerr << "invalid inner_pos for minipage/parbox"
621 string const latex_width = p.verbatim_item();
622 translate_len(latex_width, width_value, width_unit);
623 if (contains(width_unit, '\\') || contains(height_unit, '\\')) {
624 // LyX can't handle length variables
629 ss << "\\begin{minipage}";
630 if (!position.empty())
631 ss << '[' << position << ']';
632 if (!latex_height.empty())
633 ss << '[' << latex_height << ']';
634 if (!inner_pos.empty())
635 ss << '[' << inner_pos << ']';
636 ss << "{" << latex_width << "}";
639 handle_ert(os, ss.str(), parent_context);
640 parent_context.new_paragraph(os);
641 parse_text_in_inset(p, os, flags, outer, parent_context);
643 handle_ert(os, "}", parent_context);
645 handle_ert(os, "\\end{minipage}", parent_context);
647 // LyX does not like empty positions, so we have
648 // to set them to the LaTeX default values here.
649 if (position.empty())
651 if (inner_pos.empty())
652 inner_pos = position;
653 parent_context.check_layout(os);
654 begin_inset(os, "Box Frameless\n");
655 os << "position \"" << position << "\"\n";
656 os << "hor_pos \"c\"\n";
657 os << "has_inner_box 1\n";
658 os << "inner_pos \"" << inner_pos << "\"\n";
659 os << "use_parbox " << use_parbox << "\n";
660 os << "width \"" << width_value << width_unit << "\"\n";
661 os << "special \"none\"\n";
662 os << "height \"" << height_value << height_unit << "\"\n";
663 os << "height_special \"" << height_special << "\"\n";
664 os << "status open\n\n";
665 parse_text_in_inset(p, os, flags, outer, parent_context);
667 #ifdef PRESERVE_LAYOUT
668 // lyx puts a % after the end of the minipage
669 if (p.next_token().cat() == catNewline && p.next_token().cs().size() > 1) {
671 //handle_comment(os, "%dummy", parent_context);
674 parent_context.new_paragraph(os);
676 else if (p.next_token().cat() == catSpace || p.next_token().cat() == catNewline) {
677 //handle_comment(os, "%dummy", parent_context);
680 // We add a protected space if something real follows
681 if (p.good() && p.next_token().cat() != catComment) {
682 os << "\\InsetSpace ~\n";
690 /// parse an unknown environment
691 void parse_unknown_environment(Parser & p, string const & name, ostream & os,
692 unsigned flags, bool outer,
693 Context & parent_context)
695 if (name == "tabbing")
696 // We need to remember that we have to handle '\=' specially
697 flags |= FLAG_TABBING;
699 // We need to translate font changes and paragraphs inside the
700 // environment to ERT if we have a non standard font.
701 // Otherwise things like
702 // \large\begin{foo}\huge bar\end{foo}
704 bool const specialfont =
705 (parent_context.font != parent_context.normalfont);
706 bool const new_layout_allowed = parent_context.new_layout_allowed;
708 parent_context.new_layout_allowed = false;
709 handle_ert(os, "\\begin{" + name + "}", parent_context);
710 parse_text_snippet(p, os, flags, outer, parent_context);
711 handle_ert(os, "\\end{" + name + "}", parent_context);
713 parent_context.new_layout_allowed = new_layout_allowed;
717 void parse_environment(Parser & p, ostream & os, bool outer,
718 Context & parent_context)
720 LyXLayout_ptr newlayout;
721 string const name = p.getArg('{', '}');
722 const bool is_starred = suffixIs(name, '*');
723 string const unstarred_name = rtrim(name, "*");
724 active_environments.push_back(name);
726 if (is_math_env(name)) {
727 parent_context.check_layout(os);
728 begin_inset(os, "Formula ");
729 os << "\\begin{" << name << "}";
730 parse_math(p, os, FLAG_END, MATH_MODE);
731 os << "\\end{" << name << "}";
735 else if (name == "tabular" || name == "longtable") {
736 eat_whitespace(p, os, parent_context, false);
737 parent_context.check_layout(os);
738 begin_inset(os, "Tabular ");
739 handle_tabular(p, os, name == "longtable", parent_context);
744 else if (parent_context.textclass.floats().typeExist(unstarred_name)) {
745 eat_whitespace(p, os, parent_context, false);
746 parent_context.check_layout(os);
747 begin_inset(os, "Float " + unstarred_name + "\n");
748 if (p.next_token().asInput() == "[") {
749 os << "placement " << p.getArg('[', ']') << '\n';
751 os << "wide " << convert<string>(is_starred)
752 << "\nsideways false"
753 << "\nstatus open\n\n";
754 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
756 // We don't need really a new paragraph, but
757 // we must make sure that the next item gets a \begin_layout.
758 parent_context.new_paragraph(os);
762 else if (name == "minipage") {
763 eat_whitespace(p, os, parent_context, false);
764 parse_box(p, os, FLAG_END, outer, parent_context, false);
768 else if (name == "comment") {
769 eat_whitespace(p, os, parent_context, false);
770 parent_context.check_layout(os);
771 begin_inset(os, "Note Comment\n");
772 os << "status open\n";
773 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
778 else if (name == "lyxgreyedout") {
779 eat_whitespace(p, os, parent_context, false);
780 parent_context.check_layout(os);
781 begin_inset(os, "Note Greyedout\n");
782 os << "status open\n";
783 parse_text_in_inset(p, os, FLAG_END, outer, parent_context);
788 else if (!parent_context.new_layout_allowed)
789 parse_unknown_environment(p, name, os, FLAG_END, outer,
792 // Alignment settings
793 else if (name == "center" || name == "flushleft" || name == "flushright" ||
794 name == "centering" || name == "raggedright" || name == "raggedleft") {
795 eat_whitespace(p, os, parent_context, false);
796 // We must begin a new paragraph if not already done
797 if (! parent_context.atParagraphStart()) {
798 parent_context.check_end_layout(os);
799 parent_context.new_paragraph(os);
801 if (name == "flushleft" || name == "raggedright")
802 parent_context.add_extra_stuff("\\align left\n");
803 else if (name == "flushright" || name == "raggedleft")
804 parent_context.add_extra_stuff("\\align right\n");
806 parent_context.add_extra_stuff("\\align center\n");
807 parse_text(p, os, FLAG_END, outer, parent_context);
808 // Just in case the environment is empty ..
809 parent_context.extra_stuff.erase();
810 // We must begin a new paragraph to reset the alignment
811 parent_context.new_paragraph(os);
815 // The single '=' is meant here.
816 else if ((newlayout = findLayout(parent_context.textclass, name)).get() &&
817 newlayout->isEnvironment()) {
818 eat_whitespace(p, os, parent_context, false);
819 Context context(true, parent_context.textclass, newlayout,
820 parent_context.layout, parent_context.font);
821 if (parent_context.deeper_paragraph) {
822 // We are beginning a nested environment after a
823 // deeper paragraph inside the outer list environment.
824 // Therefore we don't need to output a "begin deeper".
825 context.need_end_deeper = true;
827 parent_context.check_end_layout(os);
828 switch (context.layout->latextype) {
829 case LATEX_LIST_ENVIRONMENT:
830 context.extra_stuff = "\\labelwidthstring "
831 + p.verbatim_item() + '\n';
834 case LATEX_BIB_ENVIRONMENT:
835 p.verbatim_item(); // swallow next arg
841 context.check_deeper(os);
842 parse_text(p, os, FLAG_END, outer, context);
843 context.check_end_layout(os);
844 if (parent_context.deeper_paragraph) {
845 // We must suppress the "end deeper" because we
846 // suppressed the "begin deeper" above.
847 context.need_end_deeper = false;
849 context.check_end_deeper(os);
850 parent_context.new_paragraph(os);
854 else if (name == "appendix") {
855 // This is no good latex style, but it works and is used in some documents...
856 eat_whitespace(p, os, parent_context, false);
857 parent_context.check_end_layout(os);
858 Context context(true, parent_context.textclass, parent_context.layout,
859 parent_context.layout, parent_context.font);
860 context.check_layout(os);
861 os << "\\start_of_appendix\n";
862 parse_text(p, os, FLAG_END, outer, context);
863 context.check_end_layout(os);
867 else if (known_environments.find(name) != known_environments.end()) {
868 vector<ArgumentType> arguments = known_environments[name];
869 // The last "argument" denotes wether we may translate the
870 // environment contents to LyX
871 // The default required if no argument is given makes us
872 // compatible with the reLyXre environment.
873 ArgumentType contents = arguments.empty() ?
876 if (!arguments.empty())
877 arguments.pop_back();
878 // See comment in parse_unknown_environment()
879 bool const specialfont =
880 (parent_context.font != parent_context.normalfont);
881 bool const new_layout_allowed =
882 parent_context.new_layout_allowed;
884 parent_context.new_layout_allowed = false;
885 parse_arguments("\\begin{" + name + "}", arguments, p, os,
886 outer, parent_context);
887 if (contents == verbatim)
888 handle_ert(os, p.verbatimEnvironment(name),
891 parse_text_snippet(p, os, FLAG_END, outer,
893 handle_ert(os, "\\end{" + name + "}", parent_context);
895 parent_context.new_layout_allowed = new_layout_allowed;
899 parse_unknown_environment(p, name, os, FLAG_END, outer,
902 active_environments.pop_back();
906 /// parses a comment and outputs it to \p os.
907 void parse_comment(Parser & p, ostream & os, Token const & t, Context & context)
909 BOOST_ASSERT(t.cat() == catComment);
910 if (!t.cs().empty()) {
911 context.check_layout(os);
912 handle_comment(os, '%' + t.cs(), context);
913 if (p.next_token().cat() == catNewline) {
914 // A newline after a comment line starts a new
916 if (context.new_layout_allowed) {
917 if(!context.atParagraphStart())
918 // Only start a new paragraph if not already
919 // done (we might get called recursively)
920 context.new_paragraph(os);
922 handle_ert(os, "\n", context);
923 eat_whitespace(p, os, context, true);
933 * Reads spaces and comments until the first non-space, non-comment token.
934 * New paragraphs (double newlines or \\par) are handled like simple spaces
935 * if \p eatParagraph is true.
936 * Spaces are skipped, but comments are written to \p os.
938 void eat_whitespace(Parser & p, ostream & os, Context & context,
942 Token const & t = p.get_token();
943 if (t.cat() == catComment)
944 parse_comment(p, os, t, context);
945 else if ((! eatParagraph && p.isParagraph()) ||
946 (t.cat() != catSpace && t.cat() != catNewline)) {
955 * Set a font attribute, parse text and reset the font attribute.
956 * \param attribute Attribute name (e.g. \\family, \\shape etc.)
957 * \param currentvalue Current value of the attribute. Is set to the new
958 * value during parsing.
959 * \param newvalue New value of the attribute
961 void parse_text_attributes(Parser & p, ostream & os, unsigned flags, bool outer,
962 Context & context, string const & attribute,
963 string & currentvalue, string const & newvalue)
965 context.check_layout(os);
966 string const oldvalue = currentvalue;
967 currentvalue = newvalue;
968 os << '\n' << attribute << ' ' << newvalue << "\n";
969 parse_text_snippet(p, os, flags, outer, context);
970 context.check_layout(os);
971 os << '\n' << attribute << ' ' << oldvalue << "\n";
972 currentvalue = oldvalue;
976 /// get the arguments of a natbib or jurabib citation command
977 std::pair<string, string> getCiteArguments(Parser & p, bool natbibOrder)
979 // We need to distinguish "" and "[]", so we can't use p.getOpt().
981 // text before the citation
983 // text after the citation
984 string after = p.getFullOpt();
986 if (!after.empty()) {
987 before = p.getFullOpt();
988 if (natbibOrder && !before.empty())
989 std::swap(before, after);
991 return std::make_pair(before, after);
995 /// Convert filenames with TeX macros and/or quotes to something LyX can understand
996 string const normalize_filename(string const & name)
998 Parser p(trim(name, "\""));
1001 Token const & t = p.get_token();
1002 if (t.cat() != catEscape)
1004 else if (t.cs() == "lyxdot") {
1005 // This is used by LyX for simple dots in relative
1009 } else if (t.cs() == "space") {
1019 /// Convert \p name from TeX convention (relative to master file) to LyX
1020 /// convention (relative to .lyx file) if it is relative
1021 void fix_relative_filename(string & name)
1023 if (lyx::support::absolutePath(name))
1025 // FIXME UNICODE encoding of name may be wrong (makeAbsPath expects
1027 name = makeRelPath(makeAbsPath(name, getMasterFilePath()).absFilename(),
1028 getParentFilePath());
1032 /// Parse a NoWeb Scrap section. The initial "<<" is already parsed.
1033 void parse_noweb(Parser & p, ostream & os, Context & context)
1035 // assemble the rest of the keyword
1039 Token const & t = p.get_token();
1040 if (t.asInput() == ">" && p.next_token().asInput() == ">") {
1043 scrap = (p.good() && p.next_token().asInput() == "=");
1045 name += p.get_token().asInput();
1048 name += t.asInput();
1051 if (!scrap || !context.new_layout_allowed ||
1052 !context.textclass.hasLayout("Scrap")) {
1053 cerr << "Warning: Could not interpret '" << name
1054 << "'. Ignoring it." << endl;
1058 context.check_end_layout(os);
1059 Context newcontext(true, context.textclass, context.textclass["Scrap"]);
1060 newcontext.check_layout(os);
1063 Token const & t = p.get_token();
1064 // We abuse the parser a bit, because this is no TeX syntax
1066 if (t.cat() == catEscape)
1067 os << subst(t.asInput(), "\\", "\n\\backslash\n");
1069 os << subst(t.asInput(), "\n", "\n\\newline\n");
1070 // The scrap chunk is ended by an @ at the beginning of a line.
1071 // After the @ the line may contain a comment and/or
1072 // whitespace, but nothing else.
1073 if (t.asInput() == "@" && p.prev_token().cat() == catNewline &&
1074 (p.next_token().cat() == catSpace ||
1075 p.next_token().cat() == catNewline ||
1076 p.next_token().cat() == catComment)) {
1077 while (p.good() && p.next_token().cat() == catSpace)
1078 os << p.get_token().asInput();
1079 if (p.next_token().cat() == catComment)
1080 // The comment includes a final '\n'
1081 os << p.get_token().asInput();
1083 if (p.next_token().cat() == catNewline)
1090 newcontext.check_end_layout(os);
1093 } // anonymous namespace
1096 void parse_text(Parser & p, ostream & os, unsigned flags, bool outer,
1099 LyXLayout_ptr newlayout;
1100 // Store the latest bibliographystyle (needed for bibtex inset)
1101 string bibliographystyle;
1102 bool const use_natbib = used_packages.find("natbib") != used_packages.end();
1103 bool const use_jurabib = used_packages.find("jurabib") != used_packages.end();
1105 Token const & t = p.get_token();
1108 cerr << "t: " << t << " flags: " << flags << "\n";
1111 if (flags & FLAG_ITEM) {
1112 if (t.cat() == catSpace)
1115 flags &= ~FLAG_ITEM;
1116 if (t.cat() == catBegin) {
1117 // skip the brace and collect everything to the next matching
1119 flags |= FLAG_BRACE_LAST;
1123 // handle only this single token, leave the loop if done
1124 flags |= FLAG_LEAVE;
1127 if (t.character() == ']' && (flags & FLAG_BRACK_LAST))
1133 if (t.cat() == catMath) {
1134 // we are inside some text mode thingy, so opening new math is allowed
1135 context.check_layout(os);
1136 begin_inset(os, "Formula ");
1137 Token const & n = p.get_token();
1138 if (n.cat() == catMath && outer) {
1139 // TeX's $$...$$ syntax for displayed math
1141 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1143 p.get_token(); // skip the second '$' token
1145 // simple $...$ stuff
1148 parse_math(p, os, FLAG_SIMPLE, MATH_MODE);
1154 else if (t.cat() == catSuper || t.cat() == catSub)
1155 cerr << "catcode " << t << " illegal in text mode\n";
1157 // Basic support for english quotes. This should be
1158 // extended to other quotes, but is not so easy (a
1159 // left english quote is the same as a right german
1161 else if (t.asInput() == "`"
1162 && p.next_token().asInput() == "`") {
1163 context.check_layout(os);
1164 begin_inset(os, "Quotes ");
1170 else if (t.asInput() == "'"
1171 && p.next_token().asInput() == "'") {
1172 context.check_layout(os);
1173 begin_inset(os, "Quotes ");
1180 else if (t.asInput() == "<"
1181 && p.next_token().asInput() == "<" && noweb_mode) {
1183 parse_noweb(p, os, context);
1186 else if (t.cat() == catSpace || (t.cat() == catNewline && ! p.isParagraph()))
1187 check_space(p, os, context);
1189 else if (t.character() == '[' && noweb_mode &&
1190 p.next_token().character() == '[') {
1191 // These can contain underscores
1193 string const s = p.getFullOpt() + ']';
1194 if (p.next_token().character() == ']')
1197 cerr << "Warning: Inserting missing ']' in '"
1198 << s << "'." << endl;
1199 handle_ert(os, s, context);
1202 else if (t.cat() == catLetter ||
1203 t.cat() == catOther ||
1204 t.cat() == catAlign ||
1205 t.cat() == catParameter) {
1206 // This translates "&" to "\\&" which may be wrong...
1207 context.check_layout(os);
1208 os << t.character();
1211 else if (p.isParagraph()) {
1212 if (context.new_layout_allowed)
1213 context.new_paragraph(os);
1215 handle_ert(os, "\\par ", context);
1216 eat_whitespace(p, os, context, true);
1219 else if (t.cat() == catActive) {
1220 context.check_layout(os);
1221 if (t.character() == '~') {
1222 if (context.layout->free_spacing)
1225 os << "\\InsetSpace ~\n";
1227 os << t.character();
1230 else if (t.cat() == catBegin &&
1231 p.next_token().cat() == catEnd) {
1233 Token const prev = p.prev_token();
1235 if (p.next_token().character() == '`' ||
1236 (prev.character() == '-' &&
1237 p.next_token().character() == '-'))
1238 ; // ignore it in {}`` or -{}-
1240 handle_ert(os, "{}", context);
1244 else if (t.cat() == catBegin) {
1245 context.check_layout(os);
1246 // special handling of font attribute changes
1247 Token const prev = p.prev_token();
1248 Token const next = p.next_token();
1249 Font const oldFont = context.font;
1250 if (next.character() == '[' ||
1251 next.character() == ']' ||
1252 next.character() == '*') {
1254 if (p.next_token().cat() == catEnd) {
1255 os << next.character();
1259 handle_ert(os, "{", context);
1260 parse_text_snippet(p, os,
1263 handle_ert(os, "}", context);
1265 } else if (! context.new_layout_allowed) {
1266 handle_ert(os, "{", context);
1267 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1269 handle_ert(os, "}", context);
1270 } else if (is_known(next.cs(), known_sizes)) {
1271 // next will change the size, so we must
1273 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1275 if (!context.atParagraphStart())
1277 << context.font.size << "\n";
1278 } else if (is_known(next.cs(), known_font_families)) {
1279 // next will change the font family, so we
1280 // must reset it here
1281 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1283 if (!context.atParagraphStart())
1285 << context.font.family << "\n";
1286 } else if (is_known(next.cs(), known_font_series)) {
1287 // next will change the font series, so we
1288 // must reset it here
1289 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1291 if (!context.atParagraphStart())
1293 << context.font.series << "\n";
1294 } else if (is_known(next.cs(), known_font_shapes)) {
1295 // next will change the font shape, so we
1296 // must reset it here
1297 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1299 if (!context.atParagraphStart())
1301 << context.font.shape << "\n";
1302 } else if (is_known(next.cs(), known_old_font_families) ||
1303 is_known(next.cs(), known_old_font_series) ||
1304 is_known(next.cs(), known_old_font_shapes)) {
1305 // next will change the font family, series
1306 // and shape, so we must reset it here
1307 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1309 if (!context.atParagraphStart())
1311 << context.font.family
1313 << context.font.series
1315 << context.font.shape << "\n";
1317 handle_ert(os, "{", context);
1318 parse_text_snippet(p, os, FLAG_BRACE_LAST,
1320 handle_ert(os, "}", context);
1324 else if (t.cat() == catEnd) {
1325 if (flags & FLAG_BRACE_LAST) {
1328 cerr << "stray '}' in text\n";
1329 handle_ert(os, "}", context);
1332 else if (t.cat() == catComment)
1333 parse_comment(p, os, t, context);
1336 // control sequences
1339 else if (t.cs() == "(") {
1340 context.check_layout(os);
1341 begin_inset(os, "Formula");
1343 parse_math(p, os, FLAG_SIMPLE2, MATH_MODE);
1348 else if (t.cs() == "[") {
1349 context.check_layout(os);
1350 begin_inset(os, "Formula");
1352 parse_math(p, os, FLAG_EQUATION, MATH_MODE);
1357 else if (t.cs() == "begin")
1358 parse_environment(p, os, outer, context);
1360 else if (t.cs() == "end") {
1361 if (flags & FLAG_END) {
1362 // eat environment name
1363 string const name = p.getArg('{', '}');
1364 if (name != active_environment())
1365 cerr << "\\end{" + name + "} does not match \\begin{"
1366 + active_environment() + "}\n";
1369 p.error("found 'end' unexpectedly");
1372 else if (t.cs() == "item") {
1375 bool optarg = false;
1376 if (p.next_token().character() == '[') {
1377 p.get_token(); // eat '['
1378 s = parse_text_snippet(p, FLAG_BRACK_LAST,
1383 context.check_layout(os);
1384 if (context.has_item) {
1385 // An item in an unknown list-like environment
1386 // FIXME: Do this in check_layout()!
1387 context.has_item = false;
1389 handle_ert(os, "\\item", context);
1391 handle_ert(os, "\\item ", context);
1394 if (context.layout->labeltype != LABEL_MANUAL) {
1395 // lyx does not support \item[\mybullet]
1396 // in itemize environments
1397 handle_ert(os, "[", context);
1399 handle_ert(os, "]", context);
1400 } else if (!s.empty()) {
1401 // The space is needed to separate the
1402 // item from the rest of the sentence.
1404 eat_whitespace(p, os, context, false);
1409 else if (t.cs() == "bibitem") {
1411 context.check_layout(os);
1414 os << '{' << p.verbatim_item() << '}' << "\n";
1417 else if (t.cs() == "def") {
1418 context.check_layout(os);
1419 eat_whitespace(p, os, context, false);
1420 string name = p.get_token().cs();
1421 while (p.next_token().cat() != catBegin)
1422 name += p.get_token().asString();
1423 handle_ert(os, "\\def\\" + name + '{' + p.verbatim_item() + '}', context);
1426 else if (t.cs() == "noindent") {
1428 context.add_extra_stuff("\\noindent\n");
1431 else if (t.cs() == "appendix") {
1432 context.add_extra_stuff("\\start_of_appendix\n");
1433 // We need to start a new paragraph. Otherwise the
1434 // appendix in 'bla\appendix\chapter{' would start
1436 context.new_paragraph(os);
1437 // We need to make sure that the paragraph is
1438 // generated even if it is empty. Otherwise the
1439 // appendix in '\par\appendix\par\chapter{' would
1441 context.check_layout(os);
1442 // FIXME: This is a hack to prevent paragraph
1443 // deletion if it is empty. Handle this better!
1445 "%dummy comment inserted by tex2lyx to "
1446 "ensure that this paragraph is not empty",
1448 // Both measures above may generate an additional
1449 // empty paragraph, but that does not hurt, because
1450 // whitespace does not matter here.
1451 eat_whitespace(p, os, context, true);
1454 // Must attempt to parse "Section*" before "Section".
1455 else if ((p.next_token().asInput() == "*") &&
1456 context.new_layout_allowed &&
1457 // The single '=' is meant here.
1458 (newlayout = findLayout(context.textclass,
1459 t.cs() + '*')).get() &&
1460 newlayout->isCommand()) {
1462 output_command_layout(os, p, outer, context, newlayout);
1466 // The single '=' is meant here.
1467 else if (context.new_layout_allowed &&
1468 (newlayout = findLayout(context.textclass, t.cs())).get() &&
1469 newlayout->isCommand()) {
1470 output_command_layout(os, p, outer, context, newlayout);
1474 else if (t.cs() == "includegraphics") {
1475 bool const clip = p.next_token().asInput() == "*";
1478 map<string, string> opts = split_map(p.getArg('[', ']'));
1480 opts["clip"] = string();
1481 string name = normalize_filename(p.verbatim_item());
1483 string const path = getMasterFilePath();
1484 // We want to preserve relative / absolute filenames,
1485 // therefore path is only used for testing
1486 // FIXME UNICODE encoding of name and path may be
1487 // wrong (makeAbsPath expects utf8)
1488 if (!fs::exists(makeAbsPath(name, path).toFilesystemEncoding())) {
1489 // The file extension is probably missing.
1490 // Now try to find it out.
1491 string const dvips_name =
1492 find_file(name, path,
1493 known_dvips_graphics_formats);
1494 string const pdftex_name =
1495 find_file(name, path,
1496 known_pdftex_graphics_formats);
1497 if (!dvips_name.empty()) {
1498 if (!pdftex_name.empty()) {
1499 cerr << "This file contains the "
1501 "\"\\includegraphics{"
1503 "However, files\n\""
1504 << dvips_name << "\" and\n\""
1505 << pdftex_name << "\"\n"
1506 "both exist, so I had to make a "
1507 "choice and took the first one.\n"
1508 "Please move the unwanted one "
1509 "someplace else and try again\n"
1510 "if my choice was wrong."
1514 } else if (!pdftex_name.empty())
1518 // FIXME UNICODE encoding of name and path may be
1519 // wrong (makeAbsPath expects utf8)
1520 if (fs::exists(makeAbsPath(name, path).toFilesystemEncoding()))
1521 fix_relative_filename(name);
1523 cerr << "Warning: Could not find graphics file '"
1524 << name << "'." << endl;
1526 context.check_layout(os);
1527 begin_inset(os, "Graphics ");
1528 os << "\n\tfilename " << name << '\n';
1529 if (opts.find("width") != opts.end())
1531 << translate_len(opts["width"]) << '\n';
1532 if (opts.find("height") != opts.end())
1534 << translate_len(opts["height"]) << '\n';
1535 if (opts.find("scale") != opts.end()) {
1536 istringstream iss(opts["scale"]);
1540 os << "\tscale " << val << '\n';
1542 if (opts.find("angle") != opts.end())
1543 os << "\trotateAngle "
1544 << opts["angle"] << '\n';
1545 if (opts.find("origin") != opts.end()) {
1547 string const opt = opts["origin"];
1548 if (opt.find('l') != string::npos) ss << "left";
1549 if (opt.find('r') != string::npos) ss << "right";
1550 if (opt.find('c') != string::npos) ss << "center";
1551 if (opt.find('t') != string::npos) ss << "Top";
1552 if (opt.find('b') != string::npos) ss << "Bottom";
1553 if (opt.find('B') != string::npos) ss << "Baseline";
1554 if (!ss.str().empty())
1555 os << "\trotateOrigin " << ss.str() << '\n';
1557 cerr << "Warning: Ignoring unknown includegraphics origin argument '" << opt << "'\n";
1559 if (opts.find("keepaspectratio") != opts.end())
1560 os << "\tkeepAspectRatio\n";
1561 if (opts.find("clip") != opts.end())
1563 if (opts.find("draft") != opts.end())
1565 if (opts.find("bb") != opts.end())
1566 os << "\tBoundingBox "
1567 << opts["bb"] << '\n';
1568 int numberOfbbOptions = 0;
1569 if (opts.find("bbllx") != opts.end())
1570 numberOfbbOptions++;
1571 if (opts.find("bblly") != opts.end())
1572 numberOfbbOptions++;
1573 if (opts.find("bburx") != opts.end())
1574 numberOfbbOptions++;
1575 if (opts.find("bbury") != opts.end())
1576 numberOfbbOptions++;
1577 if (numberOfbbOptions == 4)
1578 os << "\tBoundingBox "
1579 << opts["bbllx"] << opts["bblly"]
1580 << opts["bburx"] << opts["bbury"] << '\n';
1581 else if (numberOfbbOptions > 0)
1582 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1583 numberOfbbOptions = 0;
1584 if (opts.find("natwidth") != opts.end())
1585 numberOfbbOptions++;
1586 if (opts.find("natheight") != opts.end())
1587 numberOfbbOptions++;
1588 if (numberOfbbOptions == 2)
1589 os << "\tBoundingBox 0bp 0bp "
1590 << opts["natwidth"] << opts["natheight"] << '\n';
1591 else if (numberOfbbOptions > 0)
1592 cerr << "Warning: Ignoring incomplete includegraphics boundingbox arguments.\n";
1593 ostringstream special;
1594 if (opts.find("hiresbb") != opts.end())
1595 special << "hiresbb,";
1596 if (opts.find("trim") != opts.end())
1598 if (opts.find("viewport") != opts.end())
1599 special << "viewport=" << opts["viewport"] << ',';
1600 if (opts.find("totalheight") != opts.end())
1601 special << "totalheight=" << opts["totalheight"] << ',';
1602 if (opts.find("type") != opts.end())
1603 special << "type=" << opts["type"] << ',';
1604 if (opts.find("ext") != opts.end())
1605 special << "ext=" << opts["ext"] << ',';
1606 if (opts.find("read") != opts.end())
1607 special << "read=" << opts["read"] << ',';
1608 if (opts.find("command") != opts.end())
1609 special << "command=" << opts["command"] << ',';
1610 string s_special = special.str();
1611 if (!s_special.empty()) {
1612 // We had special arguments. Remove the trailing ','.
1613 os << "\tspecial " << s_special.substr(0, s_special.size() - 1) << '\n';
1615 // TODO: Handle the unknown settings better.
1616 // Warn about invalid options.
1617 // Check whether some option was given twice.
1621 else if (t.cs() == "footnote" ||
1622 (t.cs() == "thanks" && context.layout->intitle)) {
1624 context.check_layout(os);
1625 begin_inset(os, "Foot\n");
1626 os << "status collapsed\n\n";
1627 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1631 else if (t.cs() == "marginpar") {
1633 context.check_layout(os);
1634 begin_inset(os, "Marginal\n");
1635 os << "status collapsed\n\n";
1636 parse_text_in_inset(p, os, FLAG_ITEM, false, context);
1640 else if (t.cs() == "ensuremath") {
1642 context.check_layout(os);
1643 string const s = p.verbatim_item();
1644 if (s == "±" || s == "³" || s == "²" || s == "µ")
1647 handle_ert(os, "\\ensuremath{" + s + "}",
1651 else if (t.cs() == "hfill") {
1652 context.check_layout(os);
1653 os << "\n\\hfill\n";
1658 else if (t.cs() == "makeindex" || t.cs() == "maketitle") {
1659 // FIXME: Somehow prevent title layouts if
1660 // "maketitle" was not found
1662 skip_braces(p); // swallow this
1665 else if (t.cs() == "tableofcontents") {
1667 context.check_layout(os);
1668 begin_inset(os, "LatexCommand \\tableofcontents\n");
1670 skip_braces(p); // swallow this
1673 else if (t.cs() == "listoffigures") {
1675 context.check_layout(os);
1676 begin_inset(os, "FloatList figure\n");
1678 skip_braces(p); // swallow this
1681 else if (t.cs() == "listoftables") {
1683 context.check_layout(os);
1684 begin_inset(os, "FloatList table\n");
1686 skip_braces(p); // swallow this
1689 else if (t.cs() == "listof") {
1690 p.skip_spaces(true);
1691 string const name = p.get_token().asString();
1692 if (context.textclass.floats().typeExist(name)) {
1693 context.check_layout(os);
1694 begin_inset(os, "FloatList ");
1697 p.get_token(); // swallow second arg
1699 handle_ert(os, "\\listof{" + name + "}", context);
1702 else if (t.cs() == "textrm")
1703 parse_text_attributes(p, os, FLAG_ITEM, outer,
1704 context, "\\family",
1705 context.font.family, "roman");
1707 else if (t.cs() == "textsf")
1708 parse_text_attributes(p, os, FLAG_ITEM, outer,
1709 context, "\\family",
1710 context.font.family, "sans");
1712 else if (t.cs() == "texttt")
1713 parse_text_attributes(p, os, FLAG_ITEM, outer,
1714 context, "\\family",
1715 context.font.family, "typewriter");
1717 else if (t.cs() == "textmd")
1718 parse_text_attributes(p, os, FLAG_ITEM, outer,
1719 context, "\\series",
1720 context.font.series, "medium");
1722 else if (t.cs() == "textbf")
1723 parse_text_attributes(p, os, FLAG_ITEM, outer,
1724 context, "\\series",
1725 context.font.series, "bold");
1727 else if (t.cs() == "textup")
1728 parse_text_attributes(p, os, FLAG_ITEM, outer,
1730 context.font.shape, "up");
1732 else if (t.cs() == "textit")
1733 parse_text_attributes(p, os, FLAG_ITEM, outer,
1735 context.font.shape, "italic");
1737 else if (t.cs() == "textsl")
1738 parse_text_attributes(p, os, FLAG_ITEM, outer,
1740 context.font.shape, "slanted");
1742 else if (t.cs() == "textsc")
1743 parse_text_attributes(p, os, FLAG_ITEM, outer,
1745 context.font.shape, "smallcaps");
1747 else if (t.cs() == "textnormal" || t.cs() == "normalfont") {
1748 context.check_layout(os);
1749 Font oldFont = context.font;
1750 context.font.init();
1751 context.font.size = oldFont.size;
1752 os << "\n\\family " << context.font.family << "\n";
1753 os << "\n\\series " << context.font.series << "\n";
1754 os << "\n\\shape " << context.font.shape << "\n";
1755 if (t.cs() == "textnormal") {
1756 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1757 output_font_change(os, context.font, oldFont);
1758 context.font = oldFont;
1760 eat_whitespace(p, os, context, false);
1763 else if (t.cs() == "underbar") {
1764 // Do NOT handle \underline.
1765 // \underbar cuts through y, g, q, p etc.,
1766 // \underline does not.
1767 context.check_layout(os);
1768 os << "\n\\bar under\n";
1769 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1770 context.check_layout(os);
1771 os << "\n\\bar default\n";
1774 else if (t.cs() == "emph" || t.cs() == "noun") {
1775 context.check_layout(os);
1776 os << "\n\\" << t.cs() << " on\n";
1777 parse_text_snippet(p, os, FLAG_ITEM, outer, context);
1778 context.check_layout(os);
1779 os << "\n\\" << t.cs() << " default\n";
1782 else if (use_natbib &&
1783 is_known(t.cs(), known_natbib_commands) &&
1784 ((t.cs() != "citefullauthor" &&
1785 t.cs() != "citeyear" &&
1786 t.cs() != "citeyearpar") ||
1787 p.next_token().asInput() != "*")) {
1788 context.check_layout(os);
1790 // \citet[before][after]{a} \citet[after][before]{a}
1791 // \citet[before][]{a} \citet[][before]{a}
1792 // \citet[after]{a} \citet[after]{a}
1793 // \citet{a} \citet{a}
1794 string command = '\\' + t.cs();
1795 if (p.next_token().asInput() == "*") {
1799 if (command == "\\citefullauthor")
1800 // alternative name for "\\citeauthor*"
1801 command = "\\citeauthor*";
1803 // text before the citation
1805 // text after the citation
1808 boost::tie(before, after) = getCiteArguments(p, true);
1809 if (command == "\\cite") {
1810 // \cite without optional argument means
1811 // \citet, \cite with at least one optional
1812 // argument means \citep.
1813 if (before.empty() && after.empty())
1814 command = "\\citet";
1816 command = "\\citep";
1818 if (before.empty() && after == "[]")
1819 // avoid \citet[]{a}
1821 else if (before == "[]" && after == "[]") {
1822 // avoid \citet[][]{a}
1826 begin_inset(os, "LatexCommand ");
1827 os << command << after << before
1828 << '{' << p.verbatim_item() << "}\n";
1832 else if (use_jurabib &&
1833 is_known(t.cs(), known_jurabib_commands)) {
1834 context.check_layout(os);
1835 string const command = '\\' + t.cs();
1836 char argumentOrder = '\0';
1837 vector<string> const & options = used_packages["jurabib"];
1838 if (std::find(options.begin(), options.end(),
1839 "natbiborder") != options.end())
1840 argumentOrder = 'n';
1841 else if (std::find(options.begin(), options.end(),
1842 "jurabiborder") != options.end())
1843 argumentOrder = 'j';
1845 // text before the citation
1847 // text after the citation
1850 boost::tie(before, after) =
1851 getCiteArguments(p, argumentOrder != 'j');
1852 string const citation = p.verbatim_item();
1853 if (!before.empty() && argumentOrder == '\0') {
1854 cerr << "Warning: Assuming argument order "
1855 "of jurabib version 0.6 for\n'"
1856 << command << before << after << '{'
1857 << citation << "}'.\n"
1858 "Add 'jurabiborder' to the jurabib "
1859 "package options if you used an\n"
1860 "earlier jurabib version." << endl;
1862 begin_inset(os, "LatexCommand ");
1863 os << command << after << before
1864 << '{' << citation << "}\n";
1868 else if (is_known(t.cs(), known_latex_commands)) {
1869 // This needs to be after the check for natbib and
1870 // jurabib commands, because "cite" has different
1871 // arguments with natbib and jurabib.
1872 context.check_layout(os);
1873 begin_inset(os, "LatexCommand ");
1874 os << '\\' << t.cs();
1875 // lyx cannot handle newlines in a latex command
1876 // FIXME: Move the substitution into parser::getOpt()?
1877 os << subst(p.getOpt(), "\n", " ");
1878 os << subst(p.getOpt(), "\n", " ");
1879 os << '{' << subst(p.verbatim_item(), "\n", " ") << "}\n";
1883 else if (is_known(t.cs(), known_quotes)) {
1884 char const * const * where = is_known(t.cs(), known_quotes);
1885 context.check_layout(os);
1886 begin_inset(os, "Quotes ");
1887 os << known_coded_quotes[where - known_quotes];
1889 // LyX adds {} after the quote, so we have to eat
1890 // spaces here if there are any before a possible
1892 eat_whitespace(p, os, context, false);
1896 else if (is_known(t.cs(), known_sizes) &&
1897 context.new_layout_allowed) {
1898 char const * const * where = is_known(t.cs(), known_sizes);
1899 context.check_layout(os);
1900 Font const oldFont = context.font;
1901 context.font.size = known_coded_sizes[where - known_sizes];
1902 output_font_change(os, oldFont, context.font);
1903 eat_whitespace(p, os, context, false);
1906 else if (is_known(t.cs(), known_font_families) &&
1907 context.new_layout_allowed) {
1908 char const * const * where =
1909 is_known(t.cs(), known_font_families);
1910 context.check_layout(os);
1911 Font const oldFont = context.font;
1912 context.font.family =
1913 known_coded_font_families[where - known_font_families];
1914 output_font_change(os, oldFont, context.font);
1915 eat_whitespace(p, os, context, false);
1918 else if (is_known(t.cs(), known_font_series) &&
1919 context.new_layout_allowed) {
1920 char const * const * where =
1921 is_known(t.cs(), known_font_series);
1922 context.check_layout(os);
1923 Font const oldFont = context.font;
1924 context.font.series =
1925 known_coded_font_series[where - known_font_series];
1926 output_font_change(os, oldFont, context.font);
1927 eat_whitespace(p, os, context, false);
1930 else if (is_known(t.cs(), known_font_shapes) &&
1931 context.new_layout_allowed) {
1932 char const * const * where =
1933 is_known(t.cs(), known_font_shapes);
1934 context.check_layout(os);
1935 Font const oldFont = context.font;
1936 context.font.shape =
1937 known_coded_font_shapes[where - known_font_shapes];
1938 output_font_change(os, oldFont, context.font);
1939 eat_whitespace(p, os, context, false);
1941 else if (is_known(t.cs(), known_old_font_families) &&
1942 context.new_layout_allowed) {
1943 char const * const * where =
1944 is_known(t.cs(), known_old_font_families);
1945 context.check_layout(os);
1946 Font const oldFont = context.font;
1947 context.font.init();
1948 context.font.size = oldFont.size;
1949 context.font.family =
1950 known_coded_font_families[where - known_old_font_families];
1951 output_font_change(os, oldFont, context.font);
1952 eat_whitespace(p, os, context, false);
1955 else if (is_known(t.cs(), known_old_font_series) &&
1956 context.new_layout_allowed) {
1957 char const * const * where =
1958 is_known(t.cs(), known_old_font_series);
1959 context.check_layout(os);
1960 Font const oldFont = context.font;
1961 context.font.init();
1962 context.font.size = oldFont.size;
1963 context.font.series =
1964 known_coded_font_series[where - known_old_font_series];
1965 output_font_change(os, oldFont, context.font);
1966 eat_whitespace(p, os, context, false);
1969 else if (is_known(t.cs(), known_old_font_shapes) &&
1970 context.new_layout_allowed) {
1971 char const * const * where =
1972 is_known(t.cs(), known_old_font_shapes);
1973 context.check_layout(os);
1974 Font const oldFont = context.font;
1975 context.font.init();
1976 context.font.size = oldFont.size;
1977 context.font.shape =
1978 known_coded_font_shapes[where - known_old_font_shapes];
1979 output_font_change(os, oldFont, context.font);
1980 eat_whitespace(p, os, context, false);
1983 else if (t.cs() == "LyX" || t.cs() == "TeX"
1984 || t.cs() == "LaTeX") {
1985 context.check_layout(os);
1987 skip_braces(p); // eat {}
1990 else if (t.cs() == "LaTeXe") {
1991 context.check_layout(os);
1993 skip_braces(p); // eat {}
1996 else if (t.cs() == "ldots") {
1997 context.check_layout(os);
1999 os << "\\SpecialChar \\ldots{}\n";
2002 else if (t.cs() == "lyxarrow") {
2003 context.check_layout(os);
2004 os << "\\SpecialChar \\menuseparator\n";
2008 else if (t.cs() == "textcompwordmark") {
2009 context.check_layout(os);
2010 os << "\\SpecialChar \\textcompwordmark{}\n";
2014 else if (t.cs() == "@" && p.next_token().asInput() == ".") {
2015 context.check_layout(os);
2016 os << "\\SpecialChar \\@.\n";
2020 else if (t.cs() == "-") {
2021 context.check_layout(os);
2022 os << "\\SpecialChar \\-\n";
2025 else if (t.cs() == "textasciitilde") {
2026 context.check_layout(os);
2031 else if (t.cs() == "textasciicircum") {
2032 context.check_layout(os);
2037 else if (t.cs() == "textbackslash") {
2038 context.check_layout(os);
2039 os << "\n\\backslash\n";
2043 else if (t.cs() == "_" || t.cs() == "&" || t.cs() == "#"
2044 || t.cs() == "$" || t.cs() == "{" || t.cs() == "}"
2046 context.check_layout(os);
2050 else if (t.cs() == "char") {
2051 context.check_layout(os);
2052 if (p.next_token().character() == '`') {
2054 if (p.next_token().cs() == "\"") {
2059 handle_ert(os, "\\char`", context);
2062 handle_ert(os, "\\char", context);
2066 else if (t.cs() == "verb") {
2067 context.check_layout(os);
2068 char const delimiter = p.next_token().character();
2069 string const arg = p.getArg(delimiter, delimiter);
2071 oss << "\\verb" << delimiter << arg << delimiter;
2072 handle_ert(os, oss.str(), context);
2075 else if (t.cs() == "\"") {
2076 context.check_layout(os);
2077 string const name = p.verbatim_item();
2078 if (name == "a") os << 'ä';
2079 else if (name == "o") os << 'ö';
2080 else if (name == "u") os << 'ü';
2081 else if (name == "A") os << 'Ä';
2082 else if (name == "O") os << 'Ö';
2083 else if (name == "U") os << 'Ü';
2084 else handle_ert(os, "\"{" + name + "}", context);
2087 // Problem: \= creates a tabstop inside the tabbing environment
2088 // and else an accent. In the latter case we really would want
2089 // \={o} instead of \= o.
2090 else if (t.cs() == "=" && (flags & FLAG_TABBING))
2091 handle_ert(os, t.asInput(), context);
2093 else if (t.cs() == "H" || t.cs() == "c" || t.cs() == "^"
2094 || t.cs() == "'" || t.cs() == "`"
2095 || t.cs() == "~" || t.cs() == "." || t.cs() == "=") {
2096 // we need the trim as the LyX parser chokes on such spaces
2097 context.check_layout(os);
2098 os << "\\i \\" << t.cs() << "{"
2099 << trim(parse_text_snippet(p, FLAG_ITEM, outer, context), " ")
2103 else if (t.cs() == "ss") {
2104 context.check_layout(os);
2106 skip_braces(p); // eat {}
2109 else if (t.cs() == "i" || t.cs() == "j" || t.cs() == "l" ||
2111 context.check_layout(os);
2112 os << "\\i \\" << t.cs() << "{}\n";
2113 skip_braces(p); // eat {}
2116 else if (t.cs() == "\\") {
2117 context.check_layout(os);
2118 string const next = p.next_token().asInput();
2120 handle_ert(os, "\\\\" + p.getOpt(), context);
2121 else if (next == "*") {
2123 handle_ert(os, "\\\\*" + p.getOpt(), context);
2126 os << "\n\\newline\n";
2130 else if (t.cs() == "input" || t.cs() == "include"
2131 || t.cs() == "verbatiminput") {
2132 string name = '\\' + t.cs();
2133 if (t.cs() == "verbatiminput"
2134 && p.next_token().asInput() == "*")
2135 name += p.get_token().asInput();
2136 context.check_layout(os);
2137 begin_inset(os, "Include ");
2138 string filename(normalize_filename(p.getArg('{', '}')));
2139 string const path = getMasterFilePath();
2140 // We want to preserve relative / absolute filenames,
2141 // therefore path is only used for testing
2142 // FIXME UNICODE encoding of filename and path may be
2143 // wrong (makeAbsPath expects utf8)
2144 if (t.cs() == "include" &&
2145 !fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2146 // The file extension is probably missing.
2147 // Now try to find it out.
2148 string const tex_name =
2149 find_file(filename, path,
2150 known_tex_extensions);
2151 if (!tex_name.empty())
2152 filename = tex_name;
2154 // FIXME UNICODE encoding of filename and path may be
2155 // wrong (makeAbsPath expects utf8)
2156 if (fs::exists(makeAbsPath(filename, path).toFilesystemEncoding())) {
2157 string const abstexname =
2158 makeAbsPath(filename, path).absFilename();
2159 string const abslyxname =
2160 changeExtension(abstexname, ".lyx");
2161 fix_relative_filename(filename);
2162 string const lyxname =
2163 changeExtension(filename, ".lyx");
2164 if (t.cs() != "verbatiminput" &&
2165 tex2lyx(abstexname, FileName(abslyxname))) {
2166 os << name << '{' << lyxname << "}\n";
2168 os << name << '{' << filename << "}\n";
2171 cerr << "Warning: Could not find included file '"
2172 << filename << "'." << endl;
2173 os << name << '{' << filename << "}\n";
2175 os << "preview false\n";
2179 else if (t.cs() == "bibliographystyle") {
2180 // store new bibliographystyle
2181 bibliographystyle = p.verbatim_item();
2182 // output new bibliographystyle.
2183 // This is only necessary if used in some other macro than \bibliography.
2184 handle_ert(os, "\\bibliographystyle{" + bibliographystyle + "}", context);
2187 else if (t.cs() == "bibliography") {
2188 context.check_layout(os);
2189 begin_inset(os, "LatexCommand ");
2191 // Do we have a bibliographystyle set?
2192 if (!bibliographystyle.empty()) {
2193 os << '[' << bibliographystyle << ']';
2195 os << '{' << p.verbatim_item() << "}\n";
2199 else if (t.cs() == "parbox")
2200 parse_box(p, os, FLAG_ITEM, outer, context, true);
2202 else if (t.cs() == "smallskip" ||
2203 t.cs() == "medskip" ||
2204 t.cs() == "bigskip" ||
2205 t.cs() == "vfill") {
2206 context.check_layout(os);
2207 begin_inset(os, "VSpace ");
2213 else if (is_known(t.cs(), known_spaces)) {
2214 char const * const * where = is_known(t.cs(), known_spaces);
2215 context.check_layout(os);
2216 begin_inset(os, "InsetSpace ");
2217 os << '\\' << known_coded_spaces[where - known_spaces]
2219 // LaTeX swallows whitespace after all spaces except
2220 // "\\,". We have to do that here, too, because LyX
2221 // adds "{}" which would make the spaces significant.
2223 eat_whitespace(p, os, context, false);
2224 // LyX adds "{}" after all spaces except "\\ " and
2225 // "\\,", so we have to remove "{}".
2226 // "\\,{}" is equivalent to "\\," in LaTeX, so we
2227 // remove the braces after "\\,", too.
2232 else if (t.cs() == "newpage" ||
2233 t.cs() == "clearpage" ||
2234 t.cs() == "cleardoublepage") {
2235 context.check_layout(os);
2236 // FIXME: what about \\pagebreak?
2237 os << "\n\\" << t.cs() << "\n";
2238 skip_braces(p); // eat {}
2241 else if (t.cs() == "newcommand" ||
2242 t.cs() == "providecommand" ||
2243 t.cs() == "renewcommand") {
2244 // these could be handled by parse_command(), but
2245 // we need to call add_known_command() here.
2246 string name = t.asInput();
2247 if (p.next_token().asInput() == "*") {
2248 // Starred form. Eat '*'
2252 string const command = p.verbatim_item();
2253 string const opt1 = p.getOpt();
2254 string const opt2 = p.getFullOpt();
2255 add_known_command(command, opt1, !opt2.empty());
2256 string const ert = name + '{' + command + '}' +
2258 '{' + p.verbatim_item() + '}';
2259 handle_ert(os, ert, context);
2262 else if (t.cs() == "vspace") {
2263 bool starred = false;
2264 if (p.next_token().asInput() == "*") {
2268 string const length = p.verbatim_item();
2271 bool valid = splitLatexLength(length, valstring, unit);
2272 bool known_vspace = false;
2273 bool known_unit = false;
2276 istringstream iss(valstring);
2279 if (unit == "\\smallskipamount") {
2281 known_vspace = true;
2282 } else if (unit == "\\medskipamount") {
2284 known_vspace = true;
2285 } else if (unit == "\\bigskipamount") {
2287 known_vspace = true;
2288 } else if (unit == "\\fill") {
2290 known_vspace = true;
2293 if (!known_vspace) {
2294 switch (unitFromString(unit)) {
2315 if (known_unit || known_vspace) {
2316 // Literal length or known variable
2317 context.check_layout(os);
2318 begin_inset(os, "VSpace ");
2326 // LyX can't handle other length variables in Inset VSpace
2327 string name = t.asInput();
2332 handle_ert(os, name + '{' + unit + '}', context);
2333 else if (value == -1.0)
2334 handle_ert(os, name + "{-" + unit + '}', context);
2336 handle_ert(os, name + '{' + valstring + unit + '}', context);
2338 handle_ert(os, name + '{' + length + '}', context);
2343 //cerr << "#: " << t << " mode: " << mode << endl;
2344 // heuristic: read up to next non-nested space
2346 string s = t.asInput();
2347 string z = p.verbatim_item();
2348 while (p.good() && z != " " && z.size()) {
2349 //cerr << "read: " << z << endl;
2351 z = p.verbatim_item();
2353 cerr << "found ERT: " << s << endl;
2354 handle_ert(os, s + ' ', context);
2356 string name = t.asInput();
2357 if (p.next_token().asInput() == "*") {
2358 // Starred commands like \vspace*{}
2359 p.get_token(); // Eat '*'
2362 if (! parse_command(name, p, os, outer, context))
2363 handle_ert(os, name, context);
2366 if (flags & FLAG_LEAVE) {
2367 flags &= ~FLAG_LEAVE;