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_;
64 int const FORMAT = 11;
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::plain_layout_ = from_ascii("Plain Layout");
117 InsetLayout DocumentClass::plain_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
194 LexerKeyword textClassTags[] = {
195 { "addtopreamble", TC_ADDTOPREAMBLE },
196 { "classoptions", TC_CLASSOPTIONS },
197 { "columns", TC_COLUMNS },
198 { "counter", TC_COUNTER },
199 { "defaultfont", TC_DEFAULTFONT },
200 { "defaultmodule", TC_DEFAULTMODULE },
201 { "defaultstyle", TC_DEFAULTSTYLE },
202 { "excludesmodule", TC_EXCLUDESMODULE },
203 { "float", TC_FLOAT },
204 { "format", TC_FORMAT },
205 { "input", TC_INPUT },
206 { "insetlayout", TC_INSETLAYOUT },
207 { "leftmargin", TC_LEFTMARGIN },
208 { "nofloat", TC_NOFLOAT },
209 { "nostyle", TC_NOSTYLE },
210 { "outputtype", TC_OUTPUTTYPE },
211 { "pagestyle", TC_PAGESTYLE },
212 { "preamble", TC_PREAMBLE },
213 { "provides", TC_PROVIDES },
214 { "providesmodule", TC_PROVIDESMODULE },
215 { "requires", TC_REQUIRES },
216 { "rightmargin", TC_RIGHTMARGIN },
217 { "secnumdepth", TC_SECNUMDEPTH },
218 { "sides", TC_SIDES },
219 { "style", TC_STYLE },
220 { "titlelatexname", TC_TITLELATEXNAME },
221 { "titlelatextype", TC_TITLELATEXTYPE },
222 { "tocdepth", TC_TOCDEPTH }
228 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
230 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
231 FileName const tempfile = FileName::tempName("convert_layout");
232 bool success = layout2layout(filename, tempfile);
234 success = read(tempfile, rt);
235 tempfile.removeFile();
239 bool TextClass::read(FileName const & filename, ReadType rt)
241 if (!filename.isReadableFile()) {
242 lyxerr << "Cannot read layout file `" << filename << "'."
247 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
248 to_utf8(makeDisplayPath(filename.absFilename())));
250 // Define the plain layout used in table cells, ert, etc. Note that
251 // we do this before loading any layout file, so that classes can
252 // override features of this layout if they should choose to do so.
253 if (rt == BASECLASS && !hasLayout(plain_layout_))
254 layoutlist_.push_back(createBasicLayout(plain_layout_));
256 Lexer lexrc(textClassTags);
257 lexrc.setFile(filename);
258 ReturnValues retval = read(lexrc, rt);
260 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
261 to_utf8(makeDisplayPath(filename.absFilename())));
263 if (retval != FORMAT_MISMATCH)
266 bool const worx = convertLayoutFormat(filename, rt);
268 LYXERR0 ("Unable to convert " << filename <<
269 " to format " << FORMAT);
276 bool TextClass::validate(std::string const & str)
279 return tc.read(str, VALIDATION);
283 bool TextClass::read(std::string const & str, ReadType rt)
285 Lexer lexrc(textClassTags);
286 istringstream is(str);
288 ReturnValues retval = read(lexrc, rt);
290 if (retval != FORMAT_MISMATCH)
293 // write the layout string to a temporary file
294 FileName const tempfile = FileName::tempName("TextClass_read");
295 ofstream os(tempfile.toFilesystemEncoding().c_str());
297 LYXERR0("Unable to create temporary file");
303 // now try to convert it
304 bool const worx = convertLayoutFormat(tempfile, rt);
306 LYXERR0("Unable to convert internal layout information to format "
309 tempfile.removeFile();
314 // Reads a textclass structure from file.
315 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
317 bool error = !lexrc.isOK();
319 // Format of files before the 'Format' tag was introduced
323 while (lexrc.isOK() && !error) {
324 int le = lexrc.lex();
327 case Lexer::LEX_FEOF:
330 case Lexer::LEX_UNDEF:
331 lexrc.printError("Unknown TextClass tag `$$Token'");
339 switch (static_cast<TextClassTags>(le)) {
343 format = lexrc.getInteger();
346 case TC_OUTPUTTYPE: // output type definition
347 readOutputType(lexrc);
350 case TC_INPUT: // Include file
352 string const inc = lexrc.getString();
353 FileName tmp = libFileSearch("layouts", inc,
357 lexrc.printError("Could not find input file: " + inc);
359 } else if (!read(tmp, MERGE)) {
360 lexrc.printError("Error reading input"
361 "file: " + tmp.absFilename());
367 case TC_DEFAULTSTYLE:
369 docstring const name = from_utf8(subst(lexrc.getString(),
371 defaultlayout_ = name;
377 docstring const name = from_utf8(subst(lexrc.getString(),
380 string s = "Could not read name for style: `$$Token' "
381 + lexrc.getString() + " is probably not valid UTF-8!";
382 lexrc.printError(s.c_str());
384 // Since we couldn't read the name, we just scan the rest
385 // of the style and discard it.
386 error = !readStyle(lexrc, lay);
387 } else if (hasLayout(name)) {
388 Layout & lay = operator[](name);
389 error = !readStyle(lexrc, lay);
392 layout.setName(name);
393 error = !readStyle(lexrc, layout);
395 layoutlist_.push_back(layout);
397 if (defaultlayout_.empty()) {
398 // We do not have a default layout yet, so we choose
399 // the first layout we encounter.
400 defaultlayout_ = name;
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());
496 case TC_DEFAULTMODULE: {
498 string const module = lexrc.getString();
499 if (find(default_modules_.begin(), default_modules_.end(), module) == default_modules_.end())
500 default_modules_.push_back(module);
504 case TC_PROVIDESMODULE: {
506 string const module = lexrc.getString();
507 if (find(provided_modules_.begin(), provided_modules_.end(), module) == provided_modules_.end())
508 provided_modules_.push_back(module);
512 case TC_EXCLUDESMODULE: {
514 string const module = lexrc.getString();
515 // modules already have their own way to exclude other modules
517 LYXERR0("ExcludesModule tag cannot be used in a module!");
520 if (find(excluded_modules_.begin(), excluded_modules_.end(), module) == excluded_modules_.end())
521 excluded_modules_.push_back(module);
525 case TC_LEFTMARGIN: // left margin type
527 leftmargin_ = lexrc.getDocString();
530 case TC_RIGHTMARGIN: // right margin type
532 rightmargin_ = lexrc.getDocString();
538 if (il.read(lexrc, *this))
539 insetlayoutlist_[il.name()] = il;
540 // else there was an error, so forget it
550 docstring const name = lexrc.getDocString();
552 string s = "Could not read name for counter: `$$Token' "
553 + lexrc.getString() + " is probably not valid UTF-8!";
554 lexrc.printError(s.c_str());
556 // Since we couldn't read the name, we just scan the rest
560 error = !counters_.read(lexrc, name);
563 lexrc.printError("No name given for style: `$$Token'.");
568 case TC_TITLELATEXTYPE:
569 readTitleType(lexrc);
572 case TC_TITLELATEXNAME:
574 titlename_ = lexrc.getString();
579 string const nofloat = lexrc.getString();
580 floatlist_.erase(nofloat);
585 //Note that this is triggered the first time through the loop unless
586 //we hit a format tag.
587 if (format != FORMAT)
591 if (format != FORMAT)
592 return FORMAT_MISMATCH;
595 return (error ? ERROR : OK);
597 if (defaultlayout_.empty()) {
598 LYXERR0("Error: Textclass '" << name_
599 << "' is missing a defaultstyle.");
603 // Try to erase "stdinsets" from the provides_ set.
605 // Provides stdinsets 1
606 // declaration simply tells us that the standard insets have been
607 // defined. (It's found in stdinsets.inc but could also be used in
608 // user-defined files.) There isn't really any such package. So we
609 // might as well go ahead and erase it.
610 // If we do not succeed, then it was not there, which means that
611 // the textclass did not provide the definitions of the standard
612 // insets. So we need to try to load them.
613 int erased = provides_.erase("stdinsets");
615 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
618 throw ExceptionMessage(WarningException, _("Missing File"),
619 _("Could not find stdinsets.inc! This may lead to data loss!"));
621 } else if (!read(tmp, MERGE)) {
622 throw ExceptionMessage(WarningException, _("Corrupt File"),
623 _("Could not read stdinsets.inc! This may lead to data loss!"));
628 min_toclevel_ = Layout::NOT_IN_TOC;
629 max_toclevel_ = Layout::NOT_IN_TOC;
630 const_iterator lit = begin();
631 const_iterator len = end();
632 for (; lit != len; ++lit) {
633 int const toclevel = lit->toclevel;
634 if (toclevel != Layout::NOT_IN_TOC) {
635 if (min_toclevel_ == Layout::NOT_IN_TOC)
636 min_toclevel_ = toclevel;
638 min_toclevel_ = min(min_toclevel_, toclevel);
639 max_toclevel_ = max(max_toclevel_, toclevel);
642 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
643 << ", maximum is " << max_toclevel_);
645 return (error ? ERROR : OK);
649 void TextClass::readTitleType(Lexer & lexrc)
651 LexerKeyword titleTypeTags[] = {
652 { "commandafter", TITLE_COMMAND_AFTER },
653 { "environment", TITLE_ENVIRONMENT }
656 PushPopHelper pph(lexrc, titleTypeTags);
658 int le = lexrc.lex();
660 case Lexer::LEX_UNDEF:
661 lexrc.printError("Unknown output type `$$Token'");
663 case TITLE_COMMAND_AFTER:
664 case TITLE_ENVIRONMENT:
665 titletype_ = static_cast<TitleLatexType>(le);
668 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
674 void TextClass::readOutputType(Lexer & lexrc)
676 LexerKeyword outputTypeTags[] = {
677 { "docbook", DOCBOOK },
679 { "literate", LITERATE }
682 PushPopHelper pph(lexrc, outputTypeTags);
684 int le = lexrc.lex();
686 case Lexer::LEX_UNDEF:
687 lexrc.printError("Unknown output type `$$Token'");
692 outputType_ = static_cast<OutputType>(le);
695 LYXERR0("Unhandled value " << le);
701 void TextClass::readClassOptions(Lexer & lexrc)
711 LexerKeyword classOptionsTags[] = {
713 {"fontsize", CO_FONTSIZE },
714 {"header", CO_HEADER },
715 {"other", CO_OTHER },
716 {"pagestyle", CO_PAGESTYLE }
719 lexrc.pushTable(classOptionsTags);
721 while (!getout && lexrc.isOK()) {
722 int le = lexrc.lex();
724 case Lexer::LEX_UNDEF:
725 lexrc.printError("Unknown ClassOption tag `$$Token'");
732 opt_fontsize_ = rtrim(lexrc.getString());
736 opt_pagestyle_ = rtrim(lexrc.getString());
740 options_ = lexrc.getString();
744 class_header_ = subst(lexrc.getString(), """, "\"");
755 void TextClass::readFloat(Lexer & lexrc)
769 LexerKeyword floatTags[] = {
771 { "extension", FT_EXT },
772 { "guiname", FT_NAME },
773 { "latexbuiltin", FT_BUILTIN },
774 { "listname", FT_LISTNAME },
775 { "numberwithin", FT_WITHIN },
776 { "placement", FT_PLACEMENT },
777 { "style", FT_STYLE },
781 lexrc.pushTable(floatTags);
790 bool builtin = false;
793 while (!getout && lexrc.isOK()) {
794 int le = lexrc.lex();
796 case Lexer::LEX_UNDEF:
797 lexrc.printError("Unknown float tag `$$Token'");
804 type = lexrc.getString();
805 if (floatlist_.typeExist(type)) {
806 Floating const & fl = floatlist_.getType(type);
807 placement = fl.placement();
809 within = fl.within();
812 listName = fl.listName();
813 builtin = fl.builtin();
818 name = lexrc.getString();
822 placement = lexrc.getString();
826 ext = lexrc.getString();
830 within = lexrc.getString();
831 if (within == "none")
836 style = lexrc.getString();
840 listName = lexrc.getString();
844 builtin = lexrc.getBool();
852 // Here if have a full float if getout == true
854 Floating fl(type, placement, ext, within,
855 style, name, listName, builtin);
856 floatlist_.newFloat(fl);
857 // each float has its own counter
858 counters_.newCounter(from_ascii(type), from_ascii(within),
859 docstring(), docstring());
860 // also define sub-float counters
861 docstring const subtype = "sub-" + from_ascii(type);
862 counters_.newCounter(subtype, from_ascii(type),
863 "\\alph{" + subtype + "}", docstring());
870 bool TextClass::hasLayout(docstring const & n) const
872 docstring const name = n.empty() ? defaultLayoutName() : n;
874 return find_if(layoutlist_.begin(), layoutlist_.end(),
875 LayoutNamesEqual(name))
876 != layoutlist_.end();
880 Layout const & TextClass::operator[](docstring const & name) const
882 LASSERT(!name.empty(), /**/);
885 find_if(begin(), end(), LayoutNamesEqual(name));
888 lyxerr << "We failed to find the layout '" << to_utf8(name)
889 << "' in the layout list. You MUST investigate!"
891 for (const_iterator cit = begin(); cit != end(); ++cit)
892 lyxerr << " " << to_utf8(cit->name()) << endl;
894 // we require the name to exist
895 LASSERT(false, /**/);
902 Layout & TextClass::operator[](docstring const & name)
904 LASSERT(!name.empty(), /**/);
906 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
909 LYXERR0("We failed to find the layout '" << to_utf8(name)
910 << "' in the layout list. You MUST investigate!");
911 for (const_iterator cit = begin(); cit != end(); ++cit)
912 LYXERR0(" " << to_utf8(cit->name()));
914 // we require the name to exist
915 LASSERT(false, /**/);
922 bool TextClass::deleteLayout(docstring const & name)
924 if (name == defaultLayoutName() || name == plainLayoutName())
927 LayoutList::iterator it =
928 remove_if(layoutlist_.begin(), layoutlist_.end(),
929 LayoutNamesEqual(name));
931 LayoutList::iterator end = layoutlist_.end();
932 bool const ret = (it != end);
933 layoutlist_.erase(it, end);
938 // Load textclass info if not loaded yet
939 bool TextClass::load(string const & path) const
944 // Read style-file, provided path is searched before the system ones
945 // If path is a file, it is loaded directly.
946 FileName layout_file(path);
947 if (!path.empty() && !layout_file.isReadableFile())
948 layout_file = FileName(addName(path, name_ + ".layout"));
949 if (layout_file.empty() || !layout_file.exists())
950 layout_file = libFileSearch("layouts", name_, "layout");
951 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
954 lyxerr << "Error reading `"
955 << to_utf8(makeDisplayPath(layout_file.absFilename()))
956 << "'\n(Check `" << name_
957 << "')\nCheck your installation and "
958 "try Options/Reconfigure..." << endl;
965 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
968 layoutlist_.push_back(createBasicLayout(n, true));
972 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
974 // FIXME The fix for the InsetLayout part of 4812 would be here:
975 // Add the InsetLayout to the document class if it is not found.
977 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
979 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
980 if (cit != cen && cit->first == n)
982 size_t i = n.find(':');
983 if (i == string::npos)
987 return plain_insetlayout_;
991 docstring const & TextClass::defaultLayoutName() const
993 // This really should come from the actual layout... (Lgb)
994 return defaultlayout_;
998 Layout const & TextClass::defaultLayout() const
1000 return operator[](defaultLayoutName());
1004 bool TextClass::isDefaultLayout(Layout const & layout) const
1006 return layout.name() == defaultLayoutName();
1010 bool TextClass::isPlainLayout(Layout const & layout) const
1012 return layout.name() == plainLayoutName();
1016 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
1018 static Layout * defaultLayout = NULL;
1020 if (defaultLayout) {
1021 defaultLayout->setUnknown(unknown);
1022 defaultLayout->setName(name);
1023 return *defaultLayout;
1026 static char const * s = "Margin Static\n"
1027 "LatexType Paragraph\n"
1030 "AlignPossible Left, Right, Center\n"
1031 "LabelType No_Label\n"
1033 istringstream ss(s);
1034 Lexer lex(textClassTags);
1036 defaultLayout = new Layout;
1037 defaultLayout->setUnknown(unknown);
1038 defaultLayout->setName(name);
1039 if (!readStyle(lex, *defaultLayout)) {
1040 // The only way this happens is because the hardcoded layout above
1042 LASSERT(false, /**/);
1044 return *defaultLayout;
1047 /////////////////////////////////////////////////////////////////////////
1049 // DocumentClassBundle
1051 /////////////////////////////////////////////////////////////////////////
1053 DocumentClassBundle::~DocumentClassBundle()
1055 for (size_t i = 0; i != documentClasses_.size(); ++i)
1056 delete documentClasses_[i];
1057 documentClasses_.clear();
1060 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1062 DocumentClass * dc = new DocumentClass(baseClass);
1063 documentClasses_.push_back(dc);
1064 return *documentClasses_.back();
1068 DocumentClassBundle & DocumentClassBundle::get()
1070 static DocumentClassBundle singleton;
1075 /////////////////////////////////////////////////////////////////////////
1079 /////////////////////////////////////////////////////////////////////////
1081 DocumentClass::DocumentClass(LayoutFile const & tc)
1086 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1088 LayoutList::const_iterator it = layoutlist_.begin();
1089 LayoutList::const_iterator end = layoutlist_.end();
1090 for (; it != end; ++it)
1091 if (it->latexname() == lay)
1097 bool DocumentClass::provides(string const & p) const
1099 return provides_.find(p) != provides_.end();
1103 bool DocumentClass::hasTocLevels() const
1105 return min_toclevel_ != Layout::NOT_IN_TOC;
1109 /////////////////////////////////////////////////////////////////////////
1113 /////////////////////////////////////////////////////////////////////////
1115 ostream & operator<<(ostream & os, PageSides p)