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 int const FORMAT = 11;
66 bool layout2layout(FileName const & filename, FileName const & tempfile)
68 FileName const script = libFileSearch("scripts", "layout2layout.py");
70 LYXERR0("Could not find layout conversion "
71 "script layout2layout.py.");
75 ostringstream command;
76 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
77 << ' ' << quoteName(filename.toFilesystemEncoding())
78 << ' ' << quoteName(tempfile.toFilesystemEncoding());
79 string const command_str = command.str();
81 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
83 cmd_ret const ret = runCommand(command_str);
85 LYXERR0("Could not run layout conversion script layout2layout.py.");
92 std::string translateRT(TextClass::ReadType rt)
95 case TextClass::BASECLASS:
97 case TextClass::MERGE:
99 case TextClass::MODULE:
100 return "module file";
101 case TextClass::VALIDATION:
111 // This string should not be translated here,
112 // because it is a layout identifier.
113 docstring const TextClass::plain_layout_ = from_ascii("Plain Layout");
116 InsetLayout DocumentClass::plain_insetlayout_;
119 /////////////////////////////////////////////////////////////////////////
123 /////////////////////////////////////////////////////////////////////////
125 TextClass::TextClass()
132 pagestyle_ = "default";
133 defaultfont_ = sane_font;
134 opt_fontsize_ = "10|11|12";
135 opt_pagestyle_ = "empty|plain|headings|fancy";
136 titletype_ = TITLE_COMMAND_AFTER;
137 titlename_ = "maketitle";
139 _("Plain Layout"); // a hack to make this translatable
143 bool TextClass::readStyle(Lexer & lexrc, Layout & lay) const
145 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
146 if (!lay.read(lexrc, *this)) {
147 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
151 lay.resfont = lay.font;
152 lay.resfont.realize(defaultfont_);
153 lay.reslabelfont = lay.labelfont;
154 lay.reslabelfont.realize(defaultfont_);
155 return true; // no errors
193 LexerKeyword textClassTags[] = {
194 { "addtopreamble", TC_ADDTOPREAMBLE },
195 { "classoptions", TC_CLASSOPTIONS },
196 { "columns", TC_COLUMNS },
197 { "counter", TC_COUNTER },
198 { "defaultfont", TC_DEFAULTFONT },
199 { "defaultmodule", TC_DEFAULTMODULE },
200 { "defaultstyle", TC_DEFAULTSTYLE },
201 { "excludesmodule", TC_EXCLUDESMODULE },
202 { "float", TC_FLOAT },
203 { "format", TC_FORMAT },
204 { "input", TC_INPUT },
205 { "insetlayout", TC_INSETLAYOUT },
206 { "leftmargin", TC_LEFTMARGIN },
207 { "nofloat", TC_NOFLOAT },
208 { "nostyle", TC_NOSTYLE },
209 { "outputtype", TC_OUTPUTTYPE },
210 { "pagestyle", TC_PAGESTYLE },
211 { "preamble", TC_PREAMBLE },
212 { "provides", TC_PROVIDES },
213 { "providesmodule", TC_PROVIDESMODULE },
214 { "requires", TC_REQUIRES },
215 { "rightmargin", TC_RIGHTMARGIN },
216 { "secnumdepth", TC_SECNUMDEPTH },
217 { "sides", TC_SIDES },
218 { "style", TC_STYLE },
219 { "titlelatexname", TC_TITLELATEXNAME },
220 { "titlelatextype", TC_TITLELATEXTYPE },
221 { "tocdepth", TC_TOCDEPTH }
227 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
229 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
230 FileName const tempfile = FileName::tempName("convert_layout");
231 bool success = layout2layout(filename, tempfile);
233 success = read(tempfile, rt);
234 tempfile.removeFile();
238 bool TextClass::read(FileName const & filename, ReadType rt)
240 if (!filename.isReadableFile()) {
241 lyxerr << "Cannot read layout file `" << filename << "'."
246 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
247 to_utf8(makeDisplayPath(filename.absFilename())));
249 // Define the plain layout used in table cells, ert, etc. Note that
250 // we do this before loading any layout file, so that classes can
251 // override features of this layout if they should choose to do so.
252 if (rt == BASECLASS && !hasLayout(plain_layout_))
253 layoutlist_.push_back(createBasicLayout(plain_layout_));
255 Lexer lexrc(textClassTags);
256 lexrc.setFile(filename);
257 ReturnValues retval = read(lexrc, rt);
259 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
260 to_utf8(makeDisplayPath(filename.absFilename())));
262 if (retval != FORMAT_MISMATCH)
265 bool const worx = convertLayoutFormat(filename, rt);
267 LYXERR0 ("Unable to convert " << filename <<
268 " to format " << FORMAT);
275 bool TextClass::validate(std::string const & str)
278 return tc.read(str, VALIDATION);
282 bool TextClass::read(std::string const & str, ReadType rt)
284 Lexer lexrc(textClassTags);
285 istringstream is(str);
287 ReturnValues retval = read(lexrc, rt);
289 if (retval != FORMAT_MISMATCH)
292 // write the layout string to a temporary file
293 FileName const tempfile = FileName::tempName("TextClass_read");
294 ofstream os(tempfile.toFilesystemEncoding().c_str());
296 LYXERR0("Unable to create temporary file");
302 // now try to convert it
303 bool const worx = convertLayoutFormat(tempfile, rt);
305 LYXERR0("Unable to convert internal layout information to format "
308 tempfile.removeFile();
313 // Reads a textclass structure from file.
314 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
316 bool error = !lexrc.isOK();
318 // Format of files before the 'Format' tag was introduced
322 while (lexrc.isOK() && !error) {
323 int le = lexrc.lex();
326 case Lexer::LEX_FEOF:
329 case Lexer::LEX_UNDEF:
330 lexrc.printError("Unknown TextClass tag `$$Token'");
338 switch (static_cast<TextClassTags>(le)) {
342 format = lexrc.getInteger();
345 case TC_OUTPUTTYPE: // output type definition
346 readOutputType(lexrc);
349 case TC_INPUT: // Include file
351 string const inc = lexrc.getString();
352 FileName tmp = libFileSearch("layouts", inc,
356 lexrc.printError("Could not find input file: " + inc);
358 } else if (!read(tmp, MERGE)) {
359 lexrc.printError("Error reading input"
360 "file: " + tmp.absFilename());
366 case TC_DEFAULTSTYLE:
368 docstring const name = from_utf8(subst(lexrc.getString(),
370 defaultlayout_ = name;
376 lexrc.printError("No name given for style: `$$Token'.");
380 docstring const name = from_utf8(subst(lexrc.getString(),
383 string s = "Could not read name for style: `$$Token' "
384 + lexrc.getString() + " is probably not valid UTF-8!";
385 lexrc.printError(s.c_str());
387 // Since we couldn't read the name, we just scan the rest
388 // of the style and discard it.
389 error = !readStyle(lexrc, lay);
390 } else if (hasLayout(name)) {
391 Layout & lay = operator[](name);
392 error = !readStyle(lexrc, lay);
395 layout.setName(name);
396 error = !readStyle(lexrc, layout);
398 layoutlist_.push_back(layout);
400 if (defaultlayout_.empty()) {
401 // We do not have a default layout yet, so we choose
402 // the first layout we encounter.
403 defaultlayout_ = name;
411 docstring const style = from_utf8(subst(lexrc.getString(),
413 if (!deleteLayout(style))
414 lyxerr << "Cannot delete style `"
415 << to_utf8(style) << '\'' << endl;
421 columns_ = lexrc.getInteger();
426 switch (lexrc.getInteger()) {
427 case 1: sides_ = OneSide; break;
428 case 2: sides_ = TwoSides; break;
430 lyxerr << "Impossible number of page"
431 " sides, setting to one."
441 pagestyle_ = rtrim(lexrc.getString());
445 defaultfont_ = lyxRead(lexrc);
446 if (!defaultfont_.resolved()) {
447 lexrc.printError("Warning: defaultfont should "
448 "be fully instantiated!");
449 defaultfont_.realize(sane_font);
455 secnumdepth_ = lexrc.getInteger();
460 tocdepth_ = lexrc.getInteger();
463 // First step to support options
464 case TC_CLASSOPTIONS:
465 readClassOptions(lexrc);
469 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
472 case TC_ADDTOPREAMBLE:
473 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
478 string const feature = lexrc.getString();
480 if (lexrc.getInteger())
481 provides_.insert(feature);
483 provides_.erase(feature);
489 vector<string> const req
490 = getVectorFromString(lexrc.getString());
491 requires_.insert(req.begin(), req.end());
495 case TC_DEFAULTMODULE: {
497 string const module = lexrc.getString();
498 if (find(default_modules_.begin(), default_modules_.end(), module) == default_modules_.end())
499 default_modules_.push_back(module);
503 case TC_PROVIDESMODULE: {
505 string const module = lexrc.getString();
506 if (find(provided_modules_.begin(), provided_modules_.end(), module) == provided_modules_.end())
507 provided_modules_.push_back(module);
511 case TC_EXCLUDESMODULE: {
513 string const module = lexrc.getString();
514 // modules already have their own way to exclude other modules
516 LYXERR0("ExcludesModule tag cannot be used in a module!");
519 if (find(excluded_modules_.begin(), excluded_modules_.end(), module) == excluded_modules_.end())
520 excluded_modules_.push_back(module);
524 case TC_LEFTMARGIN: // left margin type
526 leftmargin_ = lexrc.getDocString();
529 case TC_RIGHTMARGIN: // right margin type
531 rightmargin_ = lexrc.getDocString();
534 case TC_INSETLAYOUT: {
536 lexrc.printError("No name given for InsetLayout: `$$Token'.");
540 docstring const name = subst(lexrc.getDocString(), '_', ' ');
542 string s = "Could not read name for InsetLayout: `$$Token' "
543 + lexrc.getString() + " is probably not valid UTF-8!";
544 lexrc.printError(s.c_str());
546 // Since we couldn't read the name, we just scan the rest
547 // of the style and discard it.
548 il.read(lexrc, *this);
550 } else if (hasInsetLayout(name)) {
551 InsetLayout & il = insetlayoutlist_[name];
552 error = !il.read(lexrc, *this);
556 error = !il.read(lexrc, *this);
558 insetlayoutlist_[name] = il;
569 docstring const name = lexrc.getDocString();
571 string s = "Could not read name for counter: `$$Token' "
572 + lexrc.getString() + " is probably not valid UTF-8!";
573 lexrc.printError(s.c_str());
575 // Since we couldn't read the name, we just scan the rest
579 error = !counters_.read(lexrc, name);
582 lexrc.printError("No name given for style: `$$Token'.");
587 case TC_TITLELATEXTYPE:
588 readTitleType(lexrc);
591 case TC_TITLELATEXNAME:
593 titlename_ = lexrc.getString();
598 string const nofloat = lexrc.getString();
599 floatlist_.erase(nofloat);
604 //Note that this is triggered the first time through the loop unless
605 //we hit a format tag.
606 if (format != FORMAT)
610 if (format != FORMAT)
611 return FORMAT_MISMATCH;
614 return (error ? ERROR : OK);
616 if (defaultlayout_.empty()) {
617 LYXERR0("Error: Textclass '" << name_
618 << "' is missing a defaultstyle.");
622 // Try to erase "stdinsets" from the provides_ set.
624 // Provides stdinsets 1
625 // declaration simply tells us that the standard insets have been
626 // defined. (It's found in stdinsets.inc but could also be used in
627 // user-defined files.) There isn't really any such package. So we
628 // might as well go ahead and erase it.
629 // If we do not succeed, then it was not there, which means that
630 // the textclass did not provide the definitions of the standard
631 // insets. So we need to try to load them.
632 int erased = provides_.erase("stdinsets");
634 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
637 throw ExceptionMessage(WarningException, _("Missing File"),
638 _("Could not find stdinsets.inc! This may lead to data loss!"));
640 } else if (!read(tmp, MERGE)) {
641 throw ExceptionMessage(WarningException, _("Corrupt File"),
642 _("Could not read stdinsets.inc! This may lead to data loss!"));
647 min_toclevel_ = Layout::NOT_IN_TOC;
648 max_toclevel_ = Layout::NOT_IN_TOC;
649 const_iterator lit = begin();
650 const_iterator len = end();
651 for (; lit != len; ++lit) {
652 int const toclevel = lit->toclevel;
653 if (toclevel != Layout::NOT_IN_TOC) {
654 if (min_toclevel_ == Layout::NOT_IN_TOC)
655 min_toclevel_ = toclevel;
657 min_toclevel_ = min(min_toclevel_, toclevel);
658 max_toclevel_ = max(max_toclevel_, toclevel);
661 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
662 << ", maximum is " << max_toclevel_);
664 return (error ? ERROR : OK);
668 void TextClass::readTitleType(Lexer & lexrc)
670 LexerKeyword titleTypeTags[] = {
671 { "commandafter", TITLE_COMMAND_AFTER },
672 { "environment", TITLE_ENVIRONMENT }
675 PushPopHelper pph(lexrc, titleTypeTags);
677 int le = lexrc.lex();
679 case Lexer::LEX_UNDEF:
680 lexrc.printError("Unknown output type `$$Token'");
682 case TITLE_COMMAND_AFTER:
683 case TITLE_ENVIRONMENT:
684 titletype_ = static_cast<TitleLatexType>(le);
687 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
693 void TextClass::readOutputType(Lexer & lexrc)
695 LexerKeyword outputTypeTags[] = {
696 { "docbook", DOCBOOK },
698 { "literate", LITERATE }
701 PushPopHelper pph(lexrc, outputTypeTags);
703 int le = lexrc.lex();
705 case Lexer::LEX_UNDEF:
706 lexrc.printError("Unknown output type `$$Token'");
711 outputType_ = static_cast<OutputType>(le);
714 LYXERR0("Unhandled value " << le);
720 void TextClass::readClassOptions(Lexer & lexrc)
730 LexerKeyword classOptionsTags[] = {
732 {"fontsize", CO_FONTSIZE },
733 {"header", CO_HEADER },
734 {"other", CO_OTHER },
735 {"pagestyle", CO_PAGESTYLE }
738 lexrc.pushTable(classOptionsTags);
740 while (!getout && lexrc.isOK()) {
741 int le = lexrc.lex();
743 case Lexer::LEX_UNDEF:
744 lexrc.printError("Unknown ClassOption tag `$$Token'");
751 opt_fontsize_ = rtrim(lexrc.getString());
755 opt_pagestyle_ = rtrim(lexrc.getString());
759 options_ = lexrc.getString();
763 class_header_ = subst(lexrc.getString(), """, "\"");
774 void TextClass::readFloat(Lexer & lexrc)
788 LexerKeyword floatTags[] = {
790 { "extension", FT_EXT },
791 { "guiname", FT_NAME },
792 { "latexbuiltin", FT_BUILTIN },
793 { "listname", FT_LISTNAME },
794 { "numberwithin", FT_WITHIN },
795 { "placement", FT_PLACEMENT },
796 { "style", FT_STYLE },
800 lexrc.pushTable(floatTags);
809 bool builtin = false;
812 while (!getout && lexrc.isOK()) {
813 int le = lexrc.lex();
815 case Lexer::LEX_UNDEF:
816 lexrc.printError("Unknown float tag `$$Token'");
823 type = lexrc.getString();
824 if (floatlist_.typeExist(type)) {
825 Floating const & fl = floatlist_.getType(type);
826 placement = fl.placement();
828 within = fl.within();
831 listName = fl.listName();
832 builtin = fl.builtin();
837 name = lexrc.getString();
841 placement = lexrc.getString();
845 ext = lexrc.getString();
849 within = lexrc.getString();
850 if (within == "none")
855 style = lexrc.getString();
859 listName = lexrc.getString();
863 builtin = lexrc.getBool();
871 // Here if have a full float if getout == true
873 Floating fl(type, placement, ext, within,
874 style, name, listName, builtin);
875 floatlist_.newFloat(fl);
876 // each float has its own counter
877 counters_.newCounter(from_ascii(type), from_ascii(within),
878 docstring(), docstring());
879 // also define sub-float counters
880 docstring const subtype = "sub-" + from_ascii(type);
881 counters_.newCounter(subtype, from_ascii(type),
882 "\\alph{" + subtype + "}", docstring());
889 bool TextClass::hasLayout(docstring const & n) const
891 docstring const name = n.empty() ? defaultLayoutName() : n;
893 return find_if(layoutlist_.begin(), layoutlist_.end(),
894 LayoutNamesEqual(name))
895 != layoutlist_.end();
899 bool TextClass::hasInsetLayout(docstring const & n) const
903 InsetLayouts::const_iterator it = insetlayoutlist_.begin();
904 InsetLayouts::const_iterator en = insetlayoutlist_.end();
905 for (; it != en; ++it)
912 Layout const & TextClass::operator[](docstring const & name) const
914 LASSERT(!name.empty(), /**/);
917 find_if(begin(), end(), LayoutNamesEqual(name));
920 lyxerr << "We failed to find the layout '" << to_utf8(name)
921 << "' in the layout list. You MUST investigate!"
923 for (const_iterator cit = begin(); cit != end(); ++cit)
924 lyxerr << " " << to_utf8(cit->name()) << endl;
926 // we require the name to exist
927 LASSERT(false, /**/);
934 Layout & TextClass::operator[](docstring const & name)
936 LASSERT(!name.empty(), /**/);
938 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
941 LYXERR0("We failed to find the layout '" << to_utf8(name)
942 << "' in the layout list. You MUST investigate!");
943 for (const_iterator cit = begin(); cit != end(); ++cit)
944 LYXERR0(" " << to_utf8(cit->name()));
946 // we require the name to exist
947 LASSERT(false, /**/);
954 bool TextClass::deleteLayout(docstring const & name)
956 if (name == defaultLayoutName() || name == plainLayoutName())
959 LayoutList::iterator it =
960 remove_if(layoutlist_.begin(), layoutlist_.end(),
961 LayoutNamesEqual(name));
963 LayoutList::iterator end = layoutlist_.end();
964 bool const ret = (it != end);
965 layoutlist_.erase(it, end);
970 // Load textclass info if not loaded yet
971 bool TextClass::load(string const & path) const
976 // Read style-file, provided path is searched before the system ones
977 // If path is a file, it is loaded directly.
978 FileName layout_file(path);
979 if (!path.empty() && !layout_file.isReadableFile())
980 layout_file = FileName(addName(path, name_ + ".layout"));
981 if (layout_file.empty() || !layout_file.exists())
982 layout_file = libFileSearch("layouts", name_, "layout");
983 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
986 lyxerr << "Error reading `"
987 << to_utf8(makeDisplayPath(layout_file.absFilename()))
988 << "'\n(Check `" << name_
989 << "')\nCheck your installation and "
990 "try Options/Reconfigure..." << endl;
997 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
1000 layoutlist_.push_back(createBasicLayout(n, true));
1004 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1006 // FIXME The fix for the InsetLayout part of 4812 would be here:
1007 // Add the InsetLayout to the document class if it is not found.
1009 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1010 while (!n.empty()) {
1011 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1012 if (cit != cen && cit->first == n)
1014 size_t i = n.find(':');
1015 if (i == string::npos)
1019 return plain_insetlayout_;
1023 docstring const & TextClass::defaultLayoutName() const
1025 // This really should come from the actual layout... (Lgb)
1026 return defaultlayout_;
1030 Layout const & TextClass::defaultLayout() const
1032 return operator[](defaultLayoutName());
1036 bool TextClass::isDefaultLayout(Layout const & layout) const
1038 return layout.name() == defaultLayoutName();
1042 bool TextClass::isPlainLayout(Layout const & layout) const
1044 return layout.name() == plainLayoutName();
1048 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
1050 static Layout * defaultLayout = NULL;
1052 if (defaultLayout) {
1053 defaultLayout->setUnknown(unknown);
1054 defaultLayout->setName(name);
1055 return *defaultLayout;
1058 static char const * s = "Margin Static\n"
1059 "LatexType Paragraph\n"
1062 "AlignPossible Left, Right, Center\n"
1063 "LabelType No_Label\n"
1065 istringstream ss(s);
1066 Lexer lex(textClassTags);
1068 defaultLayout = new Layout;
1069 defaultLayout->setUnknown(unknown);
1070 defaultLayout->setName(name);
1071 if (!readStyle(lex, *defaultLayout)) {
1072 // The only way this happens is because the hardcoded layout above
1074 LASSERT(false, /**/);
1076 return *defaultLayout;
1079 /////////////////////////////////////////////////////////////////////////
1081 // DocumentClassBundle
1083 /////////////////////////////////////////////////////////////////////////
1085 DocumentClassBundle::~DocumentClassBundle()
1087 for (size_t i = 0; i != documentClasses_.size(); ++i)
1088 delete documentClasses_[i];
1089 documentClasses_.clear();
1092 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1094 DocumentClass * dc = new DocumentClass(baseClass);
1095 documentClasses_.push_back(dc);
1096 return *documentClasses_.back();
1100 DocumentClassBundle & DocumentClassBundle::get()
1102 static DocumentClassBundle singleton;
1107 /////////////////////////////////////////////////////////////////////////
1111 /////////////////////////////////////////////////////////////////////////
1113 DocumentClass::DocumentClass(LayoutFile const & tc)
1118 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1120 LayoutList::const_iterator it = layoutlist_.begin();
1121 LayoutList::const_iterator end = layoutlist_.end();
1122 for (; it != end; ++it)
1123 if (it->latexname() == lay)
1129 bool DocumentClass::provides(string const & p) const
1131 return provides_.find(p) != provides_.end();
1135 bool DocumentClass::hasTocLevels() const
1137 return min_toclevel_ != Layout::NOT_IN_TOC;
1141 /////////////////////////////////////////////////////////////////////////
1145 /////////////////////////////////////////////////////////////////////////
1147 ostream & operator<<(ostream & os, PageSides p)