3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Jean-Marc Lasgouttes
8 * \author Angus Leeming
10 * \author André Pönitz
12 * Full author contact details are available in file CREDITS.
17 #include "TextClass.h"
19 #include "LayoutFile.h"
23 #include "FloatList.h"
28 #include "frontends/alert.h"
30 #include "support/lassert.h"
31 #include "support/debug.h"
32 #include "support/ExceptionMessage.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
44 using namespace lyx::support;
50 class LayoutNamesEqual : public unary_function<Layout, bool> {
52 LayoutNamesEqual(docstring const & name)
55 bool operator()(Layout const & c) const
57 return c.name() == name_;
67 bool layout2layout(FileName const & filename, FileName const & tempfile)
69 FileName const script = libFileSearch("scripts", "layout2layout.py");
71 LYXERR0("Could not find layout conversion "
72 "script layout2layout.py.");
76 ostringstream command;
77 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
78 << ' ' << quoteName(filename.toFilesystemEncoding())
79 << ' ' << quoteName(tempfile.toFilesystemEncoding());
80 string const command_str = command.str();
82 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
84 cmd_ret const ret = runCommand(command_str);
86 LYXERR0("Could not run layout conversion script layout2layout.py.");
93 std::string translateRT(TextClass::ReadType rt)
96 case TextClass::BASECLASS:
98 case TextClass::MERGE:
100 case TextClass::MODULE:
101 return "module file";
102 case TextClass::VALIDATION:
112 // This string should not be translated here,
113 // because it is a layout identifier.
114 docstring const TextClass::emptylayout_ = from_ascii("Plain Layout");
117 InsetLayout DocumentClass::empty_insetlayout_;
120 /////////////////////////////////////////////////////////////////////////
124 /////////////////////////////////////////////////////////////////////////
126 TextClass::TextClass()
133 pagestyle_ = "default";
134 defaultfont_ = sane_font;
135 opt_fontsize_ = "10|11|12";
136 opt_pagestyle_ = "empty|plain|headings|fancy";
137 titletype_ = TITLE_COMMAND_AFTER;
138 titlename_ = "maketitle";
140 _("Plain Layout"); // a hack to make this translatable
144 bool TextClass::readStyle(Lexer & lexrc, Layout & lay) const
146 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
147 if (!lay.read(lexrc, *this)) {
148 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
152 lay.resfont = lay.font;
153 lay.resfont.realize(defaultfont_);
154 lay.reslabelfont = lay.labelfont;
155 lay.reslabelfont.realize(defaultfont_);
156 return true; // no errors
192 LexerKeyword textClassTags[] = {
193 { "addtopreamble", TC_ADDTOPREAMBLE },
194 { "classoptions", TC_CLASSOPTIONS },
195 { "columns", TC_COLUMNS },
196 { "counter", TC_COUNTER },
197 { "defaultfont", TC_DEFAULTFONT },
198 { "defaultstyle", TC_DEFAULTSTYLE },
199 { "float", TC_FLOAT },
200 { "format", TC_FORMAT },
201 { "input", TC_INPUT },
202 { "insetlayout", TC_INSETLAYOUT },
203 { "leftmargin", TC_LEFTMARGIN },
204 { "nofloat", TC_NOFLOAT },
205 { "nostyle", TC_NOSTYLE },
206 { "outputtype", TC_OUTPUTTYPE },
207 { "pagestyle", TC_PAGESTYLE },
208 { "preamble", TC_PREAMBLE },
209 { "provides", TC_PROVIDES },
210 { "requires", TC_REQUIRES },
211 { "rightmargin", TC_RIGHTMARGIN },
212 { "secnumdepth", TC_SECNUMDEPTH },
213 { "sides", TC_SIDES },
214 { "style", TC_STYLE },
215 { "titlelatexname", TC_TITLELATEXNAME },
216 { "titlelatextype", TC_TITLELATEXTYPE },
217 { "tocdepth", TC_TOCDEPTH },
218 { "usemodule", TC_USEMODULE }
224 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
226 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
227 FileName const tempfile = FileName::tempName("convert_layout");
228 bool success = layout2layout(filename, tempfile);
230 success = read(tempfile, rt);
231 tempfile.removeFile();
235 bool TextClass::read(FileName const & filename, ReadType rt)
237 if (!filename.isReadableFile()) {
238 lyxerr << "Cannot read layout file `" << filename << "'."
243 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
244 to_utf8(makeDisplayPath(filename.absFilename())));
246 // Define the `empty' layout used in table cells, ert, etc. Note that
247 // we do this before loading any layout file, so that classes can
248 // override features of this layout if they should choose to do so.
249 if (rt == BASECLASS && !hasLayout(emptylayout_))
250 layoutlist_.push_back(createEmptyLayout(emptylayout_));
252 Lexer lexrc(textClassTags);
253 lexrc.setFile(filename);
254 ReturnValues retval = read(lexrc, rt);
256 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
257 to_utf8(makeDisplayPath(filename.absFilename())));
259 if (retval != FORMAT_MISMATCH)
262 bool const worx = convertLayoutFormat(filename, rt);
264 lyxerr << "Unable to convert " << filename <<
265 " to format " << FORMAT << std::endl;
272 bool TextClass::validate(std::string const & str)
275 return tc.read(str, VALIDATION);
279 bool TextClass::read(std::string const & str, ReadType rt)
281 Lexer lexrc(textClassTags);
282 istringstream is(str);
284 ReturnValues retval = read(lexrc, rt);
286 if (retval != FORMAT_MISMATCH)
289 // write the layout string to a temporary file
290 FileName const tempfile = FileName::tempName("TextClass_read");
291 ofstream os(tempfile.toFilesystemEncoding().c_str());
293 LYXERR0("Unable to create temporary file");
299 // now try to convert it
300 bool const worx = convertLayoutFormat(tempfile, rt);
302 LYXERR0("Unable to convert internal layout information to format "
305 tempfile.removeFile();
310 // Reads a textclass structure from file.
311 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
313 bool error = !lexrc.isOK();
315 // Format of files before the 'Format' tag was introduced
319 while (lexrc.isOK() && !error) {
320 int le = lexrc.lex();
323 case Lexer::LEX_FEOF:
326 case Lexer::LEX_UNDEF:
327 lexrc.printError("Unknown TextClass tag `$$Token'");
335 switch (static_cast<TextClassTags>(le)) {
339 format = lexrc.getInteger();
342 case TC_OUTPUTTYPE: // output type definition
343 readOutputType(lexrc);
346 case TC_INPUT: // Include file
348 string const inc = lexrc.getString();
349 FileName tmp = libFileSearch("layouts", inc,
353 lexrc.printError("Could not find input file: " + inc);
355 } else if (!read(tmp, MERGE)) {
356 lexrc.printError("Error reading input"
357 "file: " + tmp.absFilename());
363 case TC_DEFAULTSTYLE:
365 docstring const name = from_utf8(subst(lexrc.getString(),
367 defaultlayout_ = name;
373 docstring const name = from_utf8(subst(lexrc.getString(),
376 string s = "Could not read name for style: `$$Token' "
377 + lexrc.getString() + " is probably not valid UTF-8!";
378 lexrc.printError(s.c_str());
380 // Since we couldn't read the name, we just scan the rest
381 // of the style and discard it.
382 error = !readStyle(lexrc, lay);
383 } else if (hasLayout(name)) {
384 Layout & lay = operator[](name);
385 error = !readStyle(lexrc, lay);
388 layout.setName(name);
389 error = !readStyle(lexrc, layout);
391 layoutlist_.push_back(layout);
393 if (defaultlayout_.empty()) {
394 // We do not have a default layout yet, so we choose
395 // the first layout we encounter.
396 defaultlayout_ = name;
401 //FIXME Should we also eat the style here? viz:
403 //readStyle(lexrc, layout);
405 lexrc.printError("No name given for style: `$$Token'.");
412 docstring const style = from_utf8(subst(lexrc.getString(),
414 if (!deleteLayout(style))
415 lyxerr << "Cannot delete style `"
416 << to_utf8(style) << '\'' << endl;
422 columns_ = lexrc.getInteger();
427 switch (lexrc.getInteger()) {
428 case 1: sides_ = OneSide; break;
429 case 2: sides_ = TwoSides; break;
431 lyxerr << "Impossible number of page"
432 " sides, setting to one."
442 pagestyle_ = rtrim(lexrc.getString());
446 defaultfont_ = lyxRead(lexrc);
447 if (!defaultfont_.resolved()) {
448 lexrc.printError("Warning: defaultfont should "
449 "be fully instantiated!");
450 defaultfont_.realize(sane_font);
456 secnumdepth_ = lexrc.getInteger();
461 tocdepth_ = lexrc.getInteger();
464 // First step to support options
465 case TC_CLASSOPTIONS:
466 readClassOptions(lexrc);
470 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
473 case TC_ADDTOPREAMBLE:
474 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
479 string const feature = lexrc.getString();
481 if (lexrc.getInteger())
482 provides_.insert(feature);
484 provides_.erase(feature);
490 vector<string> const req
491 = getVectorFromString(lexrc.getString());
492 requires_.insert(req.begin(), req.end());
498 string const module = lexrc.getString();
499 usemod_.insert(module);
503 case TC_LEFTMARGIN: // left margin type
505 leftmargin_ = lexrc.getDocString();
508 case TC_RIGHTMARGIN: // right margin type
510 rightmargin_ = lexrc.getDocString();
516 if (il.read(lexrc, *this))
517 insetlayoutlist_[il.name()] = il;
518 // else there was an error, so forget it
530 case TC_TITLELATEXTYPE:
531 readTitleType(lexrc);
534 case TC_TITLELATEXNAME:
536 titlename_ = lexrc.getString();
541 string const nofloat = lexrc.getString();
542 floatlist_.erase(nofloat);
547 //Note that this is triggered the first time through the loop unless
548 //we hit a format tag.
549 if (format != FORMAT)
553 if (format != FORMAT)
554 return FORMAT_MISMATCH;
557 return (error ? ERROR : OK);
559 if (defaultlayout_.empty()) {
560 LYXERR0("Error: Textclass '" << name_
561 << "' is missing a defaultstyle.");
565 // Try to erase "stdinsets" from the provides_ set.
567 // Provides stdinsets 1
568 // declaration simply tells us that the standard insets have been
569 // defined. (It's found in stdinsets.inc but could also be used in
570 // user-defined files.) There isn't really any such package. So we
571 // might as well go ahead and erase it.
572 // If we do not succeed, then it was not there, which means that
573 // the textclass did not provide the definitions of the standard
574 // insets. So we need to try to load them.
575 int erased = provides_.erase("stdinsets");
577 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
580 throw ExceptionMessage(WarningException, _("Missing File"),
581 _("Could not find stdinsets.inc! This may lead to data loss!"));
583 } else if (!read(tmp, MERGE)) {
584 throw ExceptionMessage(WarningException, _("Corrupt File"),
585 _("Could not read stdinsets.inc! This may lead to data loss!"));
590 min_toclevel_ = Layout::NOT_IN_TOC;
591 max_toclevel_ = Layout::NOT_IN_TOC;
592 const_iterator lit = begin();
593 const_iterator len = end();
594 for (; lit != len; ++lit) {
595 int const toclevel = lit->toclevel;
596 if (toclevel != Layout::NOT_IN_TOC) {
597 if (min_toclevel_ == Layout::NOT_IN_TOC)
598 min_toclevel_ = toclevel;
600 min_toclevel_ = min(min_toclevel_, toclevel);
601 max_toclevel_ = max(max_toclevel_, toclevel);
604 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
605 << ", maximum is " << max_toclevel_);
607 return (error ? ERROR : OK);
611 void TextClass::readTitleType(Lexer & lexrc)
613 LexerKeyword titleTypeTags[] = {
614 { "commandafter", TITLE_COMMAND_AFTER },
615 { "environment", TITLE_ENVIRONMENT }
618 PushPopHelper pph(lexrc, titleTypeTags);
620 int le = lexrc.lex();
622 case Lexer::LEX_UNDEF:
623 lexrc.printError("Unknown output type `$$Token'");
625 case TITLE_COMMAND_AFTER:
626 case TITLE_ENVIRONMENT:
627 titletype_ = static_cast<TitleLatexType>(le);
630 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
636 void TextClass::readOutputType(Lexer & lexrc)
638 LexerKeyword outputTypeTags[] = {
639 { "docbook", DOCBOOK },
641 { "literate", LITERATE }
644 PushPopHelper pph(lexrc, outputTypeTags);
646 int le = lexrc.lex();
648 case Lexer::LEX_UNDEF:
649 lexrc.printError("Unknown output type `$$Token'");
654 outputType_ = static_cast<OutputType>(le);
657 LYXERR0("Unhandled value " << le);
663 void TextClass::readClassOptions(Lexer & lexrc)
673 LexerKeyword classOptionsTags[] = {
675 {"fontsize", CO_FONTSIZE },
676 {"header", CO_HEADER },
677 {"other", CO_OTHER },
678 {"pagestyle", CO_PAGESTYLE }
681 lexrc.pushTable(classOptionsTags);
683 while (!getout && lexrc.isOK()) {
684 int le = lexrc.lex();
686 case Lexer::LEX_UNDEF:
687 lexrc.printError("Unknown ClassOption tag `$$Token'");
694 opt_fontsize_ = rtrim(lexrc.getString());
698 opt_pagestyle_ = rtrim(lexrc.getString());
702 options_ = lexrc.getString();
706 class_header_ = subst(lexrc.getString(), """, "\"");
717 void TextClass::readFloat(Lexer & lexrc)
731 LexerKeyword floatTags[] = {
733 { "extension", FT_EXT },
734 { "guiname", FT_NAME },
735 { "latexbuiltin", FT_BUILTIN },
736 { "listname", FT_LISTNAME },
737 { "numberwithin", FT_WITHIN },
738 { "placement", FT_PLACEMENT },
739 { "style", FT_STYLE },
743 lexrc.pushTable(floatTags);
752 bool builtin = false;
755 while (!getout && lexrc.isOK()) {
756 int le = lexrc.lex();
758 case Lexer::LEX_UNDEF:
759 lexrc.printError("Unknown float tag `$$Token'");
766 type = lexrc.getString();
767 if (floatlist_.typeExist(type)) {
768 Floating const & fl = floatlist_.getType(type);
769 placement = fl.placement();
771 within = fl.within();
774 listName = fl.listName();
775 builtin = fl.builtin();
780 name = lexrc.getString();
784 placement = lexrc.getString();
788 ext = lexrc.getString();
792 within = lexrc.getString();
793 if (within == "none")
798 style = lexrc.getString();
802 listName = lexrc.getString();
806 builtin = lexrc.getBool();
814 // Here if have a full float if getout == true
816 Floating fl(type, placement, ext, within,
817 style, name, listName, builtin);
818 floatlist_.newFloat(fl);
819 // each float has its own counter
820 counters_.newCounter(from_ascii(type), from_ascii(within),
821 docstring(), docstring());
822 // also define sub-float counters
823 docstring const subtype = "sub-" + from_ascii(type);
824 counters_.newCounter(subtype, from_ascii(type),
825 "\\alph{" + subtype + "}", docstring());
832 void TextClass::readCounter(Lexer & lexrc)
838 CT_LABELSTRING_APPENDIX,
842 LexerKeyword counterTags[] = {
844 { "labelstring", CT_LABELSTRING },
845 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
847 { "within", CT_WITHIN }
850 lexrc.pushTable(counterTags);
854 docstring labelstring;
855 docstring labelstring_appendix;
858 while (!getout && lexrc.isOK()) {
859 int le = lexrc.lex();
861 case Lexer::LEX_UNDEF:
862 lexrc.printError("Unknown counter tag `$$Token'");
869 name = lexrc.getDocString();
870 if (counters_.hasCounter(name))
871 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
873 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
877 within = lexrc.getDocString();
878 if (within == "none")
883 labelstring = lexrc.getDocString();
884 labelstring_appendix = labelstring;
886 case CT_LABELSTRING_APPENDIX:
888 labelstring_appendix = lexrc.getDocString();
896 // Here if have a full counter if getout == true
898 counters_.newCounter(name, within,
899 labelstring, labelstring_appendix);
905 bool TextClass::hasLayout(docstring const & n) const
907 docstring const name = n.empty() ? defaultLayoutName() : n;
909 return find_if(layoutlist_.begin(), layoutlist_.end(),
910 LayoutNamesEqual(name))
911 != layoutlist_.end();
915 Layout const & TextClass::operator[](docstring const & name) const
917 LASSERT(!name.empty(), /**/);
920 find_if(begin(), end(), LayoutNamesEqual(name));
923 lyxerr << "We failed to find the layout '" << to_utf8(name)
924 << "' in the layout list. You MUST investigate!"
926 for (const_iterator cit = begin(); cit != end(); ++cit)
927 lyxerr << " " << to_utf8(cit->name()) << endl;
929 // we require the name to exist
930 LASSERT(false, /**/);
937 Layout & TextClass::operator[](docstring const & name)
939 LASSERT(!name.empty(), /**/);
941 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
944 LYXERR0("We failed to find the layout '" << to_utf8(name)
945 << "' in the layout list. You MUST investigate!");
946 for (const_iterator cit = begin(); cit != end(); ++cit)
947 LYXERR0(" " << to_utf8(cit->name()));
949 // we require the name to exist
950 LASSERT(false, /**/);
957 bool TextClass::deleteLayout(docstring const & name)
959 if (name == defaultLayoutName() || name == emptyLayoutName())
962 LayoutList::iterator it =
963 remove_if(layoutlist_.begin(), layoutlist_.end(),
964 LayoutNamesEqual(name));
966 LayoutList::iterator end = layoutlist_.end();
967 bool const ret = (it != end);
968 layoutlist_.erase(it, end);
973 // Load textclass info if not loaded yet
974 bool TextClass::load(string const & path) const
979 // Read style-file, provided path is searched before the system ones
980 // If path is a file, it is loaded directly.
981 FileName layout_file(path);
982 if (!path.empty() && !layout_file.isReadableFile())
983 layout_file = FileName(addName(path, name_ + ".layout"));
984 if (layout_file.empty() || !layout_file.exists())
985 layout_file = libFileSearch("layouts", name_, "layout");
986 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
989 lyxerr << "Error reading `"
990 << to_utf8(makeDisplayPath(layout_file.absFilename()))
991 << "'\n(Check `" << name_
992 << "')\nCheck your installation and "
993 "try Options/Reconfigure..." << endl;
1000 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
1003 layoutlist_.push_back(createEmptyLayout(n, true));
1007 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1009 // FIXME The fix for the InsetLayout part of 4812 would be here:
1010 // Add the InsetLayout to the document class if it is not found.
1012 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1013 while (!n.empty()) {
1014 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1015 if (cit != cen && cit->first == n)
1017 size_t i = n.find(':');
1018 if (i == string::npos)
1022 return empty_insetlayout_;
1026 docstring const & TextClass::defaultLayoutName() const
1028 // This really should come from the actual layout... (Lgb)
1029 return defaultlayout_;
1033 Layout const & TextClass::defaultLayout() const
1035 return operator[](defaultLayoutName());
1039 bool TextClass::isDefaultLayout(Layout const & layout) const
1041 return layout.name() == defaultLayoutName();
1045 bool TextClass::isPlainLayout(Layout const & layout) const
1047 return layout.name() == emptyLayoutName();
1051 Layout TextClass::createEmptyLayout(docstring const & name, bool unknown) const
1053 static Layout * defaultLayout = NULL;
1055 if (defaultLayout) {
1056 defaultLayout->setUnknown(unknown);
1057 defaultLayout->setName(name);
1058 return *defaultLayout;
1061 static char const * s = "Margin Static\n"
1062 "LatexType Paragraph\n"
1065 "AlignPossible Left, Right, Center\n"
1066 "LabelType No_Label\n"
1068 istringstream ss(s);
1069 Lexer lex(textClassTags);
1071 defaultLayout = new Layout;
1072 defaultLayout->setUnknown(unknown);
1073 defaultLayout->setName(name);
1074 if (!readStyle(lex, *defaultLayout)) {
1075 // The only way this happens is because the hardcoded layout above
1077 LASSERT(false, /**/);
1079 return *defaultLayout;
1082 /////////////////////////////////////////////////////////////////////////
1084 // DocumentClassBundle
1086 /////////////////////////////////////////////////////////////////////////
1088 DocumentClassBundle::~DocumentClassBundle()
1090 for (size_t i = 0; i != documentClasses_.size(); ++i)
1091 delete documentClasses_[i];
1092 documentClasses_.clear();
1095 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1097 DocumentClass * dc = new DocumentClass(baseClass);
1098 documentClasses_.push_back(dc);
1099 return *documentClasses_.back();
1103 DocumentClassBundle & DocumentClassBundle::get()
1105 static DocumentClassBundle singleton;
1110 /////////////////////////////////////////////////////////////////////////
1114 /////////////////////////////////////////////////////////////////////////
1116 DocumentClass::DocumentClass(LayoutFile const & tc)
1121 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1123 LayoutList::const_iterator it = layoutlist_.begin();
1124 LayoutList::const_iterator end = layoutlist_.end();
1125 for (; it != end; ++it)
1126 if (it->latexname() == lay)
1132 bool DocumentClass::provides(string const & p) const
1134 return provides_.find(p) != provides_.end();
1138 bool DocumentClass::hasTocLevels() const
1140 return min_toclevel_ != Layout::NOT_IN_TOC;
1144 /////////////////////////////////////////////////////////////////////////
1148 /////////////////////////////////////////////////////////////////////////
1150 ostream & operator<<(ostream & os, PageSides p)