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_;
63 // Keep the changes documented in the Customization manual.
64 int const FORMAT = 12;
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 lexrc.printError("No name given for style: `$$Token'.");
381 docstring const name = from_utf8(subst(lexrc.getString(),
384 string s = "Could not read name for style: `$$Token' "
385 + lexrc.getString() + " is probably not valid UTF-8!";
386 lexrc.printError(s.c_str());
388 // Since we couldn't read the name, we just scan the rest
389 // of the style and discard it.
390 error = !readStyle(lexrc, lay);
391 } else if (hasLayout(name)) {
392 Layout & lay = operator[](name);
393 error = !readStyle(lexrc, lay);
396 layout.setName(name);
397 error = !readStyle(lexrc, layout);
399 layoutlist_.push_back(layout);
401 if (defaultlayout_.empty()) {
402 // We do not have a default layout yet, so we choose
403 // the first layout we encounter.
404 defaultlayout_ = name;
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();
535 case TC_INSETLAYOUT: {
537 lexrc.printError("No name given for InsetLayout: `$$Token'.");
541 docstring const name = subst(lexrc.getDocString(), '_', ' ');
543 string s = "Could not read name for InsetLayout: `$$Token' "
544 + lexrc.getString() + " is probably not valid UTF-8!";
545 lexrc.printError(s.c_str());
547 // Since we couldn't read the name, we just scan the rest
548 // of the style and discard it.
549 il.read(lexrc, *this);
551 } else if (hasInsetLayout(name)) {
552 InsetLayout & il = insetlayoutlist_[name];
553 error = !il.read(lexrc, *this);
557 error = !il.read(lexrc, *this);
559 insetlayoutlist_[name] = il;
570 docstring const name = lexrc.getDocString();
572 string s = "Could not read name for counter: `$$Token' "
573 + lexrc.getString() + " is probably not valid UTF-8!";
574 lexrc.printError(s.c_str());
576 // Since we couldn't read the name, we just scan the rest
580 error = !counters_.read(lexrc, name);
583 lexrc.printError("No name given for style: `$$Token'.");
588 case TC_TITLELATEXTYPE:
589 readTitleType(lexrc);
592 case TC_TITLELATEXNAME:
594 titlename_ = lexrc.getString();
599 string const nofloat = lexrc.getString();
600 floatlist_.erase(nofloat);
605 //Note that this is triggered the first time through the loop unless
606 //we hit a format tag.
607 if (format != FORMAT)
611 if (format != FORMAT)
612 return FORMAT_MISMATCH;
615 return (error ? ERROR : OK);
617 if (defaultlayout_.empty()) {
618 LYXERR0("Error: Textclass '" << name_
619 << "' is missing a defaultstyle.");
623 // Try to erase "stdinsets" from the provides_ set.
625 // Provides stdinsets 1
626 // declaration simply tells us that the standard insets have been
627 // defined. (It's found in stdinsets.inc but could also be used in
628 // user-defined files.) There isn't really any such package. So we
629 // might as well go ahead and erase it.
630 // If we do not succeed, then it was not there, which means that
631 // the textclass did not provide the definitions of the standard
632 // insets. So we need to try to load them.
633 int erased = provides_.erase("stdinsets");
635 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
638 throw ExceptionMessage(WarningException, _("Missing File"),
639 _("Could not find stdinsets.inc! This may lead to data loss!"));
641 } else if (!read(tmp, MERGE)) {
642 throw ExceptionMessage(WarningException, _("Corrupt File"),
643 _("Could not read stdinsets.inc! This may lead to data loss!"));
648 min_toclevel_ = Layout::NOT_IN_TOC;
649 max_toclevel_ = Layout::NOT_IN_TOC;
650 const_iterator lit = begin();
651 const_iterator len = end();
652 for (; lit != len; ++lit) {
653 int const toclevel = lit->toclevel;
654 if (toclevel != Layout::NOT_IN_TOC) {
655 if (min_toclevel_ == Layout::NOT_IN_TOC)
656 min_toclevel_ = toclevel;
658 min_toclevel_ = min(min_toclevel_, toclevel);
659 max_toclevel_ = max(max_toclevel_, toclevel);
662 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
663 << ", maximum is " << max_toclevel_);
665 return (error ? ERROR : OK);
669 void TextClass::readTitleType(Lexer & lexrc)
671 LexerKeyword titleTypeTags[] = {
672 { "commandafter", TITLE_COMMAND_AFTER },
673 { "environment", TITLE_ENVIRONMENT }
676 PushPopHelper pph(lexrc, titleTypeTags);
678 int le = lexrc.lex();
680 case Lexer::LEX_UNDEF:
681 lexrc.printError("Unknown output type `$$Token'");
683 case TITLE_COMMAND_AFTER:
684 case TITLE_ENVIRONMENT:
685 titletype_ = static_cast<TitleLatexType>(le);
688 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
694 void TextClass::readOutputType(Lexer & lexrc)
696 LexerKeyword outputTypeTags[] = {
697 { "docbook", DOCBOOK },
699 { "literate", LITERATE }
702 PushPopHelper pph(lexrc, outputTypeTags);
704 int le = lexrc.lex();
706 case Lexer::LEX_UNDEF:
707 lexrc.printError("Unknown output type `$$Token'");
712 outputType_ = static_cast<OutputType>(le);
715 LYXERR0("Unhandled value " << le);
721 void TextClass::readClassOptions(Lexer & lexrc)
731 LexerKeyword classOptionsTags[] = {
733 {"fontsize", CO_FONTSIZE },
734 {"header", CO_HEADER },
735 {"other", CO_OTHER },
736 {"pagestyle", CO_PAGESTYLE }
739 lexrc.pushTable(classOptionsTags);
741 while (!getout && lexrc.isOK()) {
742 int le = lexrc.lex();
744 case Lexer::LEX_UNDEF:
745 lexrc.printError("Unknown ClassOption tag `$$Token'");
752 opt_fontsize_ = rtrim(lexrc.getString());
756 opt_pagestyle_ = rtrim(lexrc.getString());
760 options_ = lexrc.getString();
764 class_header_ = subst(lexrc.getString(), """, "\"");
775 void TextClass::readFloat(Lexer & lexrc)
789 LexerKeyword floatTags[] = {
791 { "extension", FT_EXT },
792 { "guiname", FT_NAME },
793 { "latexbuiltin", FT_BUILTIN },
794 { "listname", FT_LISTNAME },
795 { "numberwithin", FT_WITHIN },
796 { "placement", FT_PLACEMENT },
797 { "style", FT_STYLE },
801 lexrc.pushTable(floatTags);
810 bool builtin = false;
813 while (!getout && lexrc.isOK()) {
814 int le = lexrc.lex();
816 case Lexer::LEX_UNDEF:
817 lexrc.printError("Unknown float tag `$$Token'");
824 type = lexrc.getString();
825 if (floatlist_.typeExist(type)) {
826 Floating const & fl = floatlist_.getType(type);
827 placement = fl.placement();
829 within = fl.within();
832 listName = fl.listName();
833 builtin = fl.builtin();
838 name = lexrc.getString();
842 placement = lexrc.getString();
846 ext = lexrc.getString();
850 within = lexrc.getString();
851 if (within == "none")
856 style = lexrc.getString();
860 listName = lexrc.getString();
864 builtin = lexrc.getBool();
872 // Here if have a full float if getout == true
874 Floating fl(type, placement, ext, within,
875 style, name, listName, builtin);
876 floatlist_.newFloat(fl);
877 // each float has its own counter
878 counters_.newCounter(from_ascii(type), from_ascii(within),
879 docstring(), docstring());
880 // also define sub-float counters
881 docstring const subtype = "sub-" + from_ascii(type);
882 counters_.newCounter(subtype, from_ascii(type),
883 "\\alph{" + subtype + "}", docstring());
890 bool TextClass::hasLayout(docstring const & n) const
892 docstring const name = n.empty() ? defaultLayoutName() : n;
894 return find_if(layoutlist_.begin(), layoutlist_.end(),
895 LayoutNamesEqual(name))
896 != layoutlist_.end();
900 bool TextClass::hasInsetLayout(docstring const & n) const
904 InsetLayouts::const_iterator it = insetlayoutlist_.begin();
905 InsetLayouts::const_iterator en = insetlayoutlist_.end();
906 for (; it != en; ++it)
913 Layout const & TextClass::operator[](docstring const & name) const
915 LASSERT(!name.empty(), /**/);
918 find_if(begin(), end(), LayoutNamesEqual(name));
921 lyxerr << "We failed to find the layout '" << to_utf8(name)
922 << "' in the layout list. You MUST investigate!"
924 for (const_iterator cit = begin(); cit != end(); ++cit)
925 lyxerr << " " << to_utf8(cit->name()) << endl;
927 // we require the name to exist
928 LASSERT(false, /**/);
935 Layout & TextClass::operator[](docstring const & name)
937 LASSERT(!name.empty(), /**/);
939 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
942 LYXERR0("We failed to find the layout '" << to_utf8(name)
943 << "' in the layout list. You MUST investigate!");
944 for (const_iterator cit = begin(); cit != end(); ++cit)
945 LYXERR0(" " << to_utf8(cit->name()));
947 // we require the name to exist
948 LASSERT(false, /**/);
955 bool TextClass::deleteLayout(docstring const & name)
957 if (name == defaultLayoutName() || name == plainLayoutName())
960 LayoutList::iterator it =
961 remove_if(layoutlist_.begin(), layoutlist_.end(),
962 LayoutNamesEqual(name));
964 LayoutList::iterator end = layoutlist_.end();
965 bool const ret = (it != end);
966 layoutlist_.erase(it, end);
971 // Load textclass info if not loaded yet
972 bool TextClass::load(string const & path) const
977 // Read style-file, provided path is searched before the system ones
978 // If path is a file, it is loaded directly.
979 FileName layout_file(path);
980 if (!path.empty() && !layout_file.isReadableFile())
981 layout_file = FileName(addName(path, name_ + ".layout"));
982 if (layout_file.empty() || !layout_file.exists())
983 layout_file = libFileSearch("layouts", name_, "layout");
984 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
987 lyxerr << "Error reading `"
988 << to_utf8(makeDisplayPath(layout_file.absFilename()))
989 << "'\n(Check `" << name_
990 << "')\nCheck your installation and "
991 "try Options/Reconfigure..." << endl;
998 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
1001 layoutlist_.push_back(createBasicLayout(n, true));
1005 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1007 // FIXME The fix for the InsetLayout part of 4812 would be here:
1008 // Add the InsetLayout to the document class if it is not found.
1010 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1011 while (!n.empty()) {
1012 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1013 if (cit != cen && cit->first == n)
1015 size_t i = n.find(':');
1016 if (i == string::npos)
1020 return plain_insetlayout_;
1024 docstring const & TextClass::defaultLayoutName() const
1026 // This really should come from the actual layout... (Lgb)
1027 return defaultlayout_;
1031 Layout const & TextClass::defaultLayout() const
1033 return operator[](defaultLayoutName());
1037 bool TextClass::isDefaultLayout(Layout const & layout) const
1039 return layout.name() == defaultLayoutName();
1043 bool TextClass::isPlainLayout(Layout const & layout) const
1045 return layout.name() == plainLayoutName();
1049 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
1051 static Layout * defaultLayout = NULL;
1053 if (defaultLayout) {
1054 defaultLayout->setUnknown(unknown);
1055 defaultLayout->setName(name);
1056 return *defaultLayout;
1059 static char const * s = "Margin Static\n"
1060 "LatexType Paragraph\n"
1063 "AlignPossible Left, Right, Center\n"
1064 "LabelType No_Label\n"
1066 istringstream ss(s);
1067 Lexer lex(textClassTags);
1069 defaultLayout = new Layout;
1070 defaultLayout->setUnknown(unknown);
1071 defaultLayout->setName(name);
1072 if (!readStyle(lex, *defaultLayout)) {
1073 // The only way this happens is because the hardcoded layout above
1075 LASSERT(false, /**/);
1077 return *defaultLayout;
1080 /////////////////////////////////////////////////////////////////////////
1082 // DocumentClassBundle
1084 /////////////////////////////////////////////////////////////////////////
1086 DocumentClassBundle::~DocumentClassBundle()
1088 for (size_t i = 0; i != documentClasses_.size(); ++i)
1089 delete documentClasses_[i];
1090 documentClasses_.clear();
1093 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1095 DocumentClass * dc = new DocumentClass(baseClass);
1096 documentClasses_.push_back(dc);
1097 return *documentClasses_.back();
1101 DocumentClassBundle & DocumentClassBundle::get()
1103 static DocumentClassBundle singleton;
1108 /////////////////////////////////////////////////////////////////////////
1112 /////////////////////////////////////////////////////////////////////////
1114 DocumentClass::DocumentClass(LayoutFile const & tc)
1119 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1121 LayoutList::const_iterator it = layoutlist_.begin();
1122 LayoutList::const_iterator end = layoutlist_.end();
1123 for (; it != end; ++it)
1124 if (it->latexname() == lay)
1130 bool DocumentClass::provides(string const & p) const
1132 return provides_.find(p) != provides_.end();
1136 bool DocumentClass::hasTocLevels() const
1138 return min_toclevel_ != Layout::NOT_IN_TOC;
1142 /////////////////////////////////////////////////////////////////////////
1146 /////////////////////////////////////////////////////////////////////////
1148 ostream & operator<<(ostream & os, PageSides p)