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
191 LexerKeyword textClassTags[] = {
192 { "addtopreamble", TC_ADDTOPREAMBLE },
193 { "classoptions", TC_CLASSOPTIONS },
194 { "columns", TC_COLUMNS },
195 { "counter", TC_COUNTER },
196 { "defaultfont", TC_DEFAULTFONT },
197 { "defaultstyle", TC_DEFAULTSTYLE },
198 { "float", TC_FLOAT },
199 { "format", TC_FORMAT },
200 { "input", TC_INPUT },
201 { "insetlayout", TC_INSETLAYOUT },
202 { "leftmargin", TC_LEFTMARGIN },
203 { "nofloat", TC_NOFLOAT },
204 { "nostyle", TC_NOSTYLE },
205 { "outputtype", TC_OUTPUTTYPE },
206 { "pagestyle", TC_PAGESTYLE },
207 { "preamble", TC_PREAMBLE },
208 { "provides", TC_PROVIDES },
209 { "requires", TC_REQUIRES },
210 { "rightmargin", TC_RIGHTMARGIN },
211 { "secnumdepth", TC_SECNUMDEPTH },
212 { "sides", TC_SIDES },
213 { "style", TC_STYLE },
214 { "titlelatexname", TC_TITLELATEXNAME },
215 { "titlelatextype", TC_TITLELATEXTYPE },
216 { "tocdepth", TC_TOCDEPTH }
222 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
224 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
225 FileName const tempfile = FileName::tempName();
226 bool success = layout2layout(filename, tempfile);
228 success = read(tempfile, rt);
229 tempfile.removeFile();
233 bool TextClass::read(FileName const & filename, ReadType rt)
235 if (!filename.isReadableFile()) {
236 lyxerr << "Cannot read layout file `" << filename << "'."
241 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
242 to_utf8(makeDisplayPath(filename.absFilename())));
244 // Define the `empty' layout used in table cells, ert, etc. Note that
245 // we do this before loading any layout file, so that classes can
246 // override features of this layout if they should choose to do so.
247 if (rt == BASECLASS && !hasLayout(emptylayout_))
248 layoutlist_.push_back(createEmptyLayout(emptylayout_));
250 Lexer lexrc(textClassTags);
251 lexrc.setFile(filename);
252 ReturnValues retval = read(lexrc, rt);
254 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
255 to_utf8(makeDisplayPath(filename.absFilename())));
257 if (retval != FORMAT_MISMATCH)
260 bool const worx = convertLayoutFormat(filename, rt);
262 lyxerr << "Unable to convert " << filename <<
263 " to format " << FORMAT << std::endl;
270 bool TextClass::validate(std::string const & str)
273 return tc.read(str, VALIDATION);
277 bool TextClass::read(std::string const & str, ReadType rt)
279 Lexer lexrc(textClassTags);
280 istringstream is(str);
282 ReturnValues retval = read(lexrc, rt);
284 if (retval != FORMAT_MISMATCH)
287 // write the layout string to a temporary file
288 FileName const tempfile = FileName::tempName();
289 ofstream os(tempfile.toFilesystemEncoding().c_str());
291 LYXERR0("Unable to create tempoary file");
297 // now try to convert it
298 bool const worx = convertLayoutFormat(tempfile, rt);
300 LYXERR0("Unable to convert internal layout information to format "
303 tempfile.removeFile();
308 // Reads a textclass structure from file.
309 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
311 bool error = !lexrc.isOK();
313 // Format of files before the 'Format' tag was introduced
317 while (lexrc.isOK() && !error) {
318 int le = lexrc.lex();
321 case Lexer::LEX_FEOF:
324 case Lexer::LEX_UNDEF:
325 lexrc.printError("Unknown TextClass tag `$$Token'");
333 switch (static_cast<TextClassTags>(le)) {
337 format = lexrc.getInteger();
340 case TC_OUTPUTTYPE: // output type definition
341 readOutputType(lexrc);
344 case TC_INPUT: // Include file
346 string const inc = lexrc.getString();
347 FileName tmp = libFileSearch("layouts", inc,
351 lexrc.printError("Could not find input file: " + inc);
353 } else if (!read(tmp, MERGE)) {
354 lexrc.printError("Error reading input"
355 "file: " + tmp.absFilename());
361 case TC_DEFAULTSTYLE:
363 docstring const name = from_utf8(subst(lexrc.getString(),
365 defaultlayout_ = name;
371 docstring const name = from_utf8(subst(lexrc.getString(),
374 string s = "Could not read name for style: `$$Token' "
375 + lexrc.getString() + " is probably not valid UTF-8!";
376 lexrc.printError(s.c_str());
378 // Since we couldn't read the name, we just scan the rest
379 // of the style and discard it.
380 error = !readStyle(lexrc, lay);
381 } else if (hasLayout(name)) {
382 Layout & lay = operator[](name);
383 error = !readStyle(lexrc, lay);
386 layout.setName(name);
387 error = !readStyle(lexrc, layout);
389 layoutlist_.push_back(layout);
391 if (defaultlayout_.empty()) {
392 // We do not have a default layout yet, so we choose
393 // the first layout we encounter.
394 defaultlayout_ = name;
399 //FIXME Should we also eat the style here? viz:
401 //readStyle(lexrc, layout);
403 lexrc.printError("No name given for style: `$$Token'.");
410 docstring const style = from_utf8(subst(lexrc.getString(),
412 if (!deleteLayout(style))
413 lyxerr << "Cannot delete style `"
414 << to_utf8(style) << '\'' << endl;
420 columns_ = lexrc.getInteger();
425 switch (lexrc.getInteger()) {
426 case 1: sides_ = OneSide; break;
427 case 2: sides_ = TwoSides; break;
429 lyxerr << "Impossible number of page"
430 " sides, setting to one."
440 pagestyle_ = rtrim(lexrc.getString());
444 defaultfont_ = lyxRead(lexrc);
445 if (!defaultfont_.resolved()) {
446 lexrc.printError("Warning: defaultfont should "
447 "be fully instantiated!");
448 defaultfont_.realize(sane_font);
454 secnumdepth_ = lexrc.getInteger();
459 tocdepth_ = lexrc.getInteger();
462 // First step to support options
463 case TC_CLASSOPTIONS:
464 readClassOptions(lexrc);
468 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
471 case TC_ADDTOPREAMBLE:
472 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
477 string const feature = lexrc.getString();
479 if (lexrc.getInteger())
480 provides_.insert(feature);
482 provides_.erase(feature);
488 vector<string> const req
489 = getVectorFromString(lexrc.getString());
490 requires_.insert(req.begin(), req.end());
494 case TC_LEFTMARGIN: // left margin type
496 leftmargin_ = lexrc.getDocString();
499 case TC_RIGHTMARGIN: // right margin type
501 rightmargin_ = lexrc.getDocString();
508 insetlayoutlist_[il.name()] = il;
509 // else there was an error, so forget it
521 case TC_TITLELATEXTYPE:
522 readTitleType(lexrc);
525 case TC_TITLELATEXNAME:
527 titlename_ = lexrc.getString();
532 string const nofloat = lexrc.getString();
533 floatlist_.erase(nofloat);
538 //Note that this is triggered the first time through the loop unless
539 //we hit a format tag.
540 if (format != FORMAT)
544 if (format != FORMAT)
545 return FORMAT_MISMATCH;
548 return (error ? ERROR : OK);
550 if (defaultlayout_.empty()) {
551 LYXERR0("Error: Textclass '" << name_
552 << "' is missing a defaultstyle.");
556 // Try to erase "stdinsets" from the provides_ set.
558 // Provides stdinsets 1
559 // declaration simply tells us that the standard insets have been
560 // defined. (It's found in stdinsets.inc but could also be used in
561 // user-defined files.) There isn't really any such package. So we
562 // might as well go ahead and erase it.
563 // If we do not succeed, then it was not there, which means that
564 // the textclass did not provide the definitions of the standard
565 // insets. So we need to try to load them.
566 int erased = provides_.erase("stdinsets");
568 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
571 throw ExceptionMessage(WarningException, _("Missing File"),
572 _("Could not find stdinsets.inc! This may lead to data loss!"));
574 } else if (!read(tmp, MERGE)) {
575 throw ExceptionMessage(WarningException, _("Corrupt File"),
576 _("Could not read stdinsets.inc! This may lead to data loss!"));
581 min_toclevel_ = Layout::NOT_IN_TOC;
582 max_toclevel_ = Layout::NOT_IN_TOC;
583 const_iterator lit = begin();
584 const_iterator len = end();
585 for (; lit != len; ++lit) {
586 int const toclevel = lit->toclevel;
587 if (toclevel != Layout::NOT_IN_TOC) {
588 if (min_toclevel_ == Layout::NOT_IN_TOC)
589 min_toclevel_ = toclevel;
591 min_toclevel_ = min(min_toclevel_, toclevel);
592 max_toclevel_ = max(max_toclevel_, toclevel);
595 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
596 << ", maximum is " << max_toclevel_);
598 return (error ? ERROR : OK);
602 void TextClass::readTitleType(Lexer & lexrc)
604 LexerKeyword titleTypeTags[] = {
605 { "commandafter", TITLE_COMMAND_AFTER },
606 { "environment", TITLE_ENVIRONMENT }
609 PushPopHelper pph(lexrc, titleTypeTags);
611 int le = lexrc.lex();
613 case Lexer::LEX_UNDEF:
614 lexrc.printError("Unknown output type `$$Token'");
616 case TITLE_COMMAND_AFTER:
617 case TITLE_ENVIRONMENT:
618 titletype_ = static_cast<TitleLatexType>(le);
621 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
627 void TextClass::readOutputType(Lexer & lexrc)
629 LexerKeyword outputTypeTags[] = {
630 { "docbook", DOCBOOK },
632 { "literate", LITERATE }
635 PushPopHelper pph(lexrc, outputTypeTags);
637 int le = lexrc.lex();
639 case Lexer::LEX_UNDEF:
640 lexrc.printError("Unknown output type `$$Token'");
645 outputType_ = static_cast<OutputType>(le);
648 LYXERR0("Unhandled value " << le);
654 void TextClass::readClassOptions(Lexer & lexrc)
664 LexerKeyword classOptionsTags[] = {
666 {"fontsize", CO_FONTSIZE },
667 {"header", CO_HEADER },
668 {"other", CO_OTHER },
669 {"pagestyle", CO_PAGESTYLE }
672 lexrc.pushTable(classOptionsTags);
674 while (!getout && lexrc.isOK()) {
675 int le = lexrc.lex();
677 case Lexer::LEX_UNDEF:
678 lexrc.printError("Unknown ClassOption tag `$$Token'");
685 opt_fontsize_ = rtrim(lexrc.getString());
689 opt_pagestyle_ = rtrim(lexrc.getString());
693 options_ = lexrc.getString();
697 class_header_ = subst(lexrc.getString(), """, "\"");
708 void TextClass::readFloat(Lexer & lexrc)
722 LexerKeyword floatTags[] = {
724 { "extension", FT_EXT },
725 { "guiname", FT_NAME },
726 { "latexbuiltin", FT_BUILTIN },
727 { "listname", FT_LISTNAME },
728 { "numberwithin", FT_WITHIN },
729 { "placement", FT_PLACEMENT },
730 { "style", FT_STYLE },
734 lexrc.pushTable(floatTags);
743 bool builtin = false;
746 while (!getout && lexrc.isOK()) {
747 int le = lexrc.lex();
749 case Lexer::LEX_UNDEF:
750 lexrc.printError("Unknown float tag `$$Token'");
757 type = lexrc.getString();
758 if (floatlist_.typeExist(type)) {
759 Floating const & fl = floatlist_.getType(type);
760 placement = fl.placement();
762 within = fl.within();
765 listName = fl.listName();
766 builtin = fl.builtin();
771 name = lexrc.getString();
775 placement = lexrc.getString();
779 ext = lexrc.getString();
783 within = lexrc.getString();
784 if (within == "none")
789 style = lexrc.getString();
793 listName = lexrc.getString();
797 builtin = lexrc.getBool();
805 // Here if have a full float if getout == true
807 Floating fl(type, placement, ext, within,
808 style, name, listName, builtin);
809 floatlist_.newFloat(fl);
810 // each float has its own counter
811 counters_.newCounter(from_ascii(type), from_ascii(within),
812 docstring(), docstring());
813 // also define sub-float counters
814 docstring const subtype = "sub-" + from_ascii(type);
815 counters_.newCounter(subtype, from_ascii(type),
816 "\\alph{" + subtype + "}", docstring());
823 void TextClass::readCounter(Lexer & lexrc)
829 CT_LABELSTRING_APPENDIX,
833 LexerKeyword counterTags[] = {
835 { "labelstring", CT_LABELSTRING },
836 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
838 { "within", CT_WITHIN }
841 lexrc.pushTable(counterTags);
845 docstring labelstring;
846 docstring labelstring_appendix;
849 while (!getout && lexrc.isOK()) {
850 int le = lexrc.lex();
852 case Lexer::LEX_UNDEF:
853 lexrc.printError("Unknown counter tag `$$Token'");
860 name = lexrc.getDocString();
861 if (counters_.hasCounter(name))
862 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
864 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
868 within = lexrc.getDocString();
869 if (within == "none")
874 labelstring = lexrc.getDocString();
875 labelstring_appendix = labelstring;
877 case CT_LABELSTRING_APPENDIX:
879 labelstring_appendix = lexrc.getDocString();
887 // Here if have a full counter if getout == true
889 counters_.newCounter(name, within,
890 labelstring, labelstring_appendix);
896 bool TextClass::hasLayout(docstring const & n) const
898 docstring const name = n.empty() ? defaultLayoutName() : n;
900 return find_if(layoutlist_.begin(), layoutlist_.end(),
901 LayoutNamesEqual(name))
902 != layoutlist_.end();
906 Layout const & TextClass::operator[](docstring const & name) const
908 LASSERT(!name.empty(), /**/);
911 find_if(begin(), end(), LayoutNamesEqual(name));
914 lyxerr << "We failed to find the layout '" << to_utf8(name)
915 << "' in the layout list. You MUST investigate!"
917 for (const_iterator cit = begin(); cit != end(); ++cit)
918 lyxerr << " " << to_utf8(cit->name()) << endl;
920 // we require the name to exist
921 LASSERT(false, /**/);
928 Layout & TextClass::operator[](docstring const & name)
930 LASSERT(!name.empty(), /**/);
932 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
935 LYXERR0("We failed to find the layout '" << to_utf8(name)
936 << "' in the layout list. You MUST investigate!");
937 for (const_iterator cit = begin(); cit != end(); ++cit)
938 LYXERR0(" " << to_utf8(cit->name()));
940 // we require the name to exist
941 LASSERT(false, /**/);
948 bool TextClass::deleteLayout(docstring const & name)
950 if (name == defaultLayoutName() || name == emptyLayoutName())
953 LayoutList::iterator it =
954 remove_if(layoutlist_.begin(), layoutlist_.end(),
955 LayoutNamesEqual(name));
957 LayoutList::iterator end = layoutlist_.end();
958 bool const ret = (it != end);
959 layoutlist_.erase(it, end);
964 // Load textclass info if not loaded yet
965 bool TextClass::load(string const & path) const
970 // Read style-file, provided path is searched before the system ones
971 // If path is a file, it is loaded directly.
972 FileName layout_file(path);
973 if (!path.empty() && !layout_file.isReadableFile())
974 layout_file = FileName(addName(path, name_ + ".layout"));
975 if (layout_file.empty() || !layout_file.exists())
976 layout_file = libFileSearch("layouts", name_, "layout");
977 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
980 lyxerr << "Error reading `"
981 << to_utf8(makeDisplayPath(layout_file.absFilename()))
982 << "'\n(Check `" << name_
983 << "')\nCheck your installation and "
984 "try Options/Reconfigure..." << endl;
991 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
994 layoutlist_.push_back(createEmptyLayout(n, true));
998 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1000 // FIXME The fix for the InsetLayout part of 4812 would be here:
1001 // Add the InsetLayout to the document class if it is not found.
1003 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1004 while (!n.empty()) {
1005 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1006 if (cit != cen && cit->first == n)
1008 size_t i = n.find(':');
1009 if (i == string::npos)
1013 return empty_insetlayout_;
1017 docstring const & TextClass::defaultLayoutName() const
1019 // This really should come from the actual layout... (Lgb)
1020 return defaultlayout_;
1024 Layout const & TextClass::defaultLayout() const
1026 return operator[](defaultLayoutName());
1030 bool TextClass::isDefaultLayout(Layout const & layout) const
1032 return layout.name() == defaultLayoutName();
1036 bool TextClass::isPlainLayout(Layout const & layout) const
1038 return layout.name() == emptyLayoutName();
1042 Layout TextClass::createEmptyLayout(docstring const & name, bool unknown) const
1044 static Layout * defaultLayout = NULL;
1046 if (defaultLayout) {
1047 defaultLayout->setUnknown(unknown);
1048 defaultLayout->setName(name);
1049 return *defaultLayout;
1052 static char const * s = "Margin Static\n"
1053 "LatexType Paragraph\n"
1056 "AlignPossible Left, Right, Center\n"
1057 "LabelType No_Label\n"
1059 istringstream ss(s);
1060 Lexer lex(textClassTags);
1062 defaultLayout = new Layout;
1063 defaultLayout->setUnknown(unknown);
1064 defaultLayout->setName(name);
1065 if (!readStyle(lex, *defaultLayout)) {
1066 // The only way this happens is because the hardcoded layout above
1068 LASSERT(false, /**/);
1070 return *defaultLayout;
1073 /////////////////////////////////////////////////////////////////////////
1075 // DocumentClassBundle
1077 /////////////////////////////////////////////////////////////////////////
1079 DocumentClassBundle::~DocumentClassBundle()
1081 for (size_t i = 0; i != documentClasses_.size(); ++i)
1082 delete documentClasses_[i];
1083 documentClasses_.clear();
1086 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1088 DocumentClass * dc = new DocumentClass(baseClass);
1089 documentClasses_.push_back(dc);
1090 return *documentClasses_.back();
1094 DocumentClassBundle & DocumentClassBundle::get()
1096 static DocumentClassBundle singleton;
1101 /////////////////////////////////////////////////////////////////////////
1105 /////////////////////////////////////////////////////////////////////////
1107 DocumentClass::DocumentClass(LayoutFile const & tc)
1112 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1114 LayoutList::const_iterator it = layoutlist_.begin();
1115 LayoutList::const_iterator end = layoutlist_.end();
1116 for (; it != end; ++it)
1117 if (it->latexname() == lay)
1123 bool DocumentClass::provides(string const & p) const
1125 return provides_.find(p) != provides_.end();
1129 bool DocumentClass::hasTocLevels() const
1131 return min_toclevel_ != Layout::NOT_IN_TOC;
1135 /////////////////////////////////////////////////////////////////////////
1139 /////////////////////////////////////////////////////////////////////////
1141 ostream & operator<<(ostream & os, PageSides p)