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/debug.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/FileName.h"
33 #include "support/filetools.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
42 #include "boost/assert.hpp"
45 using namespace lyx::support;
51 class LayoutNamesEqual : public unary_function<Layout, bool> {
53 LayoutNamesEqual(docstring const & name)
56 bool operator()(Layout const & c) const
58 return c.name() == name_;
68 bool layout2layout(FileName const & filename, FileName const & tempfile)
70 FileName const script = libFileSearch("scripts", "layout2layout.py");
72 lyxerr << "Could not find layout conversion "
73 "script layout2layout.py." << endl;
77 ostringstream command;
78 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
79 << ' ' << quoteName(filename.toFilesystemEncoding())
80 << ' ' << quoteName(tempfile.toFilesystemEncoding());
81 string const command_str = command.str();
83 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
86 runCommand(command_str);
88 lyxerr << "Could not run layout conversion "
89 "script layout2layout.py." << endl;
96 std::string translateRT(TextClass::ReadType rt)
99 case TextClass::BASECLASS:
101 case TextClass::MERGE:
103 case TextClass::MODULE:
104 return "module file";
105 case TextClass::VALIDATION:
115 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
118 InsetLayout DocumentClass::empty_insetlayout_;
121 TextClass::TextClass()
128 pagestyle_ = "default";
129 defaultfont_ = sane_font;
130 opt_fontsize_ = "10|11|12";
131 opt_pagestyle_ = "empty|plain|headings|fancy";
132 titletype_ = TITLE_COMMAND_AFTER;
133 titlename_ = "maketitle";
135 // a hack to make this available for translation
136 // i'm sure there must be a better way (rgh)
141 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
143 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
144 if (!lay.read(lexrc, *this)) {
145 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
149 lay.resfont = lay.font;
150 lay.resfont.realize(defaultfont_);
151 lay.reslabelfont = lay.labelfont;
152 lay.reslabelfont.realize(defaultfont_);
153 return true; // no errors
188 keyword_item textClassTags[] = {
189 { "classoptions", TC_CLASSOPTIONS },
190 { "columns", TC_COLUMNS },
191 { "counter", TC_COUNTER },
192 { "defaultfont", TC_DEFAULTFONT },
193 { "defaultstyle", TC_DEFAULTSTYLE },
194 { "environment", TC_ENVIRONMENT },
195 { "float", TC_FLOAT },
196 { "format", TC_FORMAT },
197 { "input", TC_INPUT },
198 { "insetlayout", TC_INSETLAYOUT },
199 { "leftmargin", TC_LEFTMARGIN },
200 { "nofloat", TC_NOFLOAT },
201 { "nostyle", TC_NOSTYLE },
202 { "outputtype", TC_OUTPUTTYPE },
203 { "pagestyle", TC_PAGESTYLE },
204 { "preamble", TC_PREAMBLE },
205 { "provides", TC_PROVIDES },
206 { "requires", TC_REQUIRES },
207 { "rightmargin", TC_RIGHTMARGIN },
208 { "secnumdepth", TC_SECNUMDEPTH },
209 { "sides", TC_SIDES },
210 { "style", TC_STYLE },
211 { "titlelatexname", TC_TITLELATEXNAME },
212 { "titlelatextype", TC_TITLELATEXTYPE },
213 { "tocdepth", TC_TOCDEPTH }
219 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
221 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
222 FileName const tempfile = FileName::tempName();
223 bool success = layout2layout(filename, tempfile);
225 success = read(tempfile, rt);
226 tempfile.removeFile();
230 bool TextClass::read(FileName const & filename, ReadType rt)
232 if (!filename.isReadableFile()) {
233 lyxerr << "Cannot read layout file `" << filename << "'."
238 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
239 to_utf8(makeDisplayPath(filename.absFilename())));
241 // Define the `empty' layout used in table cells, ert, etc. Note that
242 // we do this before loading any layout file, so that classes can
243 // override features of this layout if they should choose to do so.
244 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
245 static char const * s = "Margin Static\n"
246 "LatexType Paragraph\n"
249 "AlignPossible Left, Right, Center\n"
250 "LabelType No_Label\n"
253 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
256 lay.setName(emptylayout_);
257 if (!readStyle(lex, lay)) {
258 // The only way this happens is because the hardcoded layout above
262 layoutlist_.push_back(lay);
264 Lexer lexrc(textClassTags,
265 sizeof(textClassTags) / sizeof(textClassTags[0]));
267 lexrc.setFile(filename);
268 ReturnValues retval = read(lexrc, rt);
270 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
271 to_utf8(makeDisplayPath(filename.absFilename())));
273 if (retval != FORMAT_MISMATCH)
276 bool const worx = convertLayoutFormat(filename, rt);
278 lyxerr << "Unable to convert " << filename <<
279 " to format " << FORMAT << std::endl;
286 bool TextClass::validate(std::string const & str)
289 return tc.read(str, VALIDATION);
293 bool TextClass::read(std::string const & str, ReadType rt)
295 Lexer lexrc(textClassTags,
296 sizeof(textClassTags) / sizeof(textClassTags[0]));
297 istringstream is(str);
299 ReturnValues retval = read(lexrc, rt);
301 if (retval != FORMAT_MISMATCH)
304 // write the layout string to a temporary file
305 FileName const tempfile = FileName::tempName();
306 ofstream os(tempfile.toFilesystemEncoding().c_str());
308 lyxerr << "Unable to create tempoary file in TextClass::read!!"
315 // now try to convert it
316 bool const worx = convertLayoutFormat(tempfile, rt);
318 lyxerr << "Unable to convert internal layout information to format "
319 << FORMAT << std::endl;
321 tempfile.removeFile();
326 // Reads a textclass structure from file.
327 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
329 bool error = !lexrc.isOK();
331 // Format of files before the 'Format' tag was introduced
335 while (lexrc.isOK() && !error) {
336 int le = lexrc.lex();
339 case Lexer::LEX_FEOF:
342 case Lexer::LEX_UNDEF:
343 lexrc.printError("Unknown TextClass tag `$$Token'");
351 switch (static_cast<TextClassTags>(le)) {
355 format = lexrc.getInteger();
358 case TC_OUTPUTTYPE: // output type definition
359 readOutputType(lexrc);
362 case TC_INPUT: // Include file
364 string const inc = lexrc.getString();
365 FileName tmp = libFileSearch("layouts", inc,
369 lexrc.printError("Could not find input file: " + inc);
371 } else if (!read(tmp, MERGE)) {
372 lexrc.printError("Error reading input"
373 "file: " + tmp.absFilename());
379 case TC_DEFAULTSTYLE:
381 docstring const name = from_utf8(subst(lexrc.getString(),
383 defaultlayout_ = name;
390 docstring const name = from_utf8(subst(lexrc.getString(),
393 string s = "Could not read name for style: `$$Token' "
394 + lexrc.getString() + " is probably not valid UTF-8!";
395 lexrc.printError(s.c_str());
397 // Since we couldn't read the name, we just scan the rest
398 // of the style and discard it.
399 error = !readStyle(lexrc, lay);
400 } else if (hasLayout(name)) {
401 Layout & lay = operator[](name);
402 error = !readStyle(lexrc, lay);
406 if (le == TC_ENVIRONMENT)
407 lay.is_environment = true;
408 error = !readStyle(lexrc, lay);
410 layoutlist_.push_back(lay);
412 if (defaultlayout_.empty()) {
413 // We do not have a default layout yet, so we choose
414 // the first layout we encounter.
415 defaultlayout_ = name;
420 //FIXME Should we also eat the style here? viz:
422 //readStyle(lexrc, lay);
424 lexrc.printError("No name given for style: `$$Token'.");
431 docstring const style = from_utf8(subst(lexrc.getString(),
433 if (!deleteLayout(style))
434 lyxerr << "Cannot delete style `"
435 << to_utf8(style) << '\'' << endl;
441 columns_ = lexrc.getInteger();
446 switch (lexrc.getInteger()) {
447 case 1: sides_ = OneSide; break;
448 case 2: sides_ = TwoSides; break;
450 lyxerr << "Impossible number of page"
451 " sides, setting to one."
461 pagestyle_ = rtrim(lexrc.getString());
465 defaultfont_ = lyxRead(lexrc);
466 if (!defaultfont_.resolved()) {
467 lexrc.printError("Warning: defaultfont should "
468 "be fully instantiated!");
469 defaultfont_.realize(sane_font);
475 secnumdepth_ = lexrc.getInteger();
480 tocdepth_ = lexrc.getInteger();
483 // First step to support options
484 case TC_CLASSOPTIONS:
485 readClassOptions(lexrc);
489 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
494 string const feature = lexrc.getString();
496 if (lexrc.getInteger())
497 provides_.insert(feature);
499 provides_.erase(feature);
505 vector<string> const req
506 = getVectorFromString(lexrc.getString());
507 requires_.insert(req.begin(), req.end());
511 case TC_LEFTMARGIN: // left margin type
513 leftmargin_ = lexrc.getDocString();
516 case TC_RIGHTMARGIN: // right margin type
518 rightmargin_ = lexrc.getDocString();
524 if (il.read(lexrc)) {
525 insetlayoutlist_[il.name()] = il;
527 // else there was an error, so forget it
539 case TC_TITLELATEXTYPE:
540 readTitleType(lexrc);
543 case TC_TITLELATEXNAME:
545 titlename_ = lexrc.getString();
550 string const nofloat = lexrc.getString();
551 floatlist_.erase(nofloat);
556 //Note that this is triggered the first time through the loop unless
557 //we hit a format tag.
558 if (format != FORMAT)
562 if (format != FORMAT)
563 return FORMAT_MISMATCH;
566 return (error ? ERROR : OK);
568 if (defaultlayout_.empty()) {
569 lyxerr << "Error: Textclass '" << name_
570 << "' is missing a defaultstyle." << endl;
574 //Try to erase "stdinsets" from the provides_ set.
576 // Provides stdinsets 1
577 //declaration simply tells us that the standard insets have been
578 //defined. (It's found in stdinsets.inc but could also be used in
579 //user-defined files.) There isn't really any such package. So we
580 //might as well go ahead and erase it.
581 //If we do not succeed, then it was not there, which means that
582 //the textclass did not provide the definitions of the standard
583 //insets. So we need to try to load them.
584 int erased = provides_.erase("stdinsets");
586 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
589 throw ExceptionMessage(WarningException, _("Missing File"),
590 _("Could not find stdinsets.inc! This may lead to data loss!"));
592 } else if (!read(tmp, MERGE)) {
593 throw ExceptionMessage(WarningException, _("Corrupt File"),
594 _("Could not read stdinsets.inc! This may lead to data loss!"));
599 min_toclevel_ = Layout::NOT_IN_TOC;
600 max_toclevel_ = Layout::NOT_IN_TOC;
601 const_iterator lit = begin();
602 const_iterator len = end();
603 for (; lit != len; ++lit) {
604 int const toclevel = lit->toclevel;
605 if (toclevel != Layout::NOT_IN_TOC) {
606 if (min_toclevel_ == Layout::NOT_IN_TOC)
607 min_toclevel_ = toclevel;
609 min_toclevel_ = min(min_toclevel_, toclevel);
610 max_toclevel_ = max(max_toclevel_, toclevel);
613 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
614 << ", maximum is " << max_toclevel_);
616 return (error ? ERROR : OK);
620 void TextClass::readTitleType(Lexer & lexrc)
622 keyword_item titleTypeTags[] = {
623 { "commandafter", TITLE_COMMAND_AFTER },
624 { "environment", TITLE_ENVIRONMENT }
627 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
629 int le = lexrc.lex();
631 case Lexer::LEX_UNDEF:
632 lexrc.printError("Unknown output type `$$Token'");
634 case TITLE_COMMAND_AFTER:
635 case TITLE_ENVIRONMENT:
636 titletype_ = static_cast<TitleLatexType>(le);
639 lyxerr << "Unhandled value " << le
640 << " in TextClass::readTitleType." << endl;
647 void TextClass::readOutputType(Lexer & lexrc)
649 keyword_item outputTypeTags[] = {
650 { "docbook", DOCBOOK },
652 { "literate", LITERATE }
655 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
657 int le = lexrc.lex();
659 case Lexer::LEX_UNDEF:
660 lexrc.printError("Unknown output type `$$Token'");
665 outputType_ = static_cast<OutputType>(le);
668 lyxerr << "Unhandled value " << le
669 << " in TextClass::readOutputType." << endl;
676 enum ClassOptionsTags {
685 void TextClass::readClassOptions(Lexer & lexrc)
687 keyword_item classOptionsTags[] = {
689 {"fontsize", CO_FONTSIZE },
690 {"header", CO_HEADER },
691 {"other", CO_OTHER },
692 {"pagestyle", CO_PAGESTYLE }
695 lexrc.pushTable(classOptionsTags, CO_END);
697 while (!getout && lexrc.isOK()) {
698 int le = lexrc.lex();
700 case Lexer::LEX_UNDEF:
701 lexrc.printError("Unknown ClassOption tag `$$Token'");
705 switch (static_cast<ClassOptionsTags>(le)) {
708 opt_fontsize_ = rtrim(lexrc.getString());
712 opt_pagestyle_ = rtrim(lexrc.getString());
716 options_ = lexrc.getString();
720 class_header_ = subst(lexrc.getString(), """, "\"");
744 void TextClass::readFloat(Lexer & lexrc)
746 keyword_item floatTags[] = {
748 { "extension", FT_EXT },
749 { "guiname", FT_NAME },
750 { "latexbuiltin", FT_BUILTIN },
751 { "listname", FT_LISTNAME },
752 { "numberwithin", FT_WITHIN },
753 { "placement", FT_PLACEMENT },
754 { "style", FT_STYLE },
758 lexrc.pushTable(floatTags, FT_END);
767 bool builtin = false;
770 while (!getout && lexrc.isOK()) {
771 int le = lexrc.lex();
773 case Lexer::LEX_UNDEF:
774 lexrc.printError("Unknown float tag `$$Token'");
778 switch (static_cast<FloatTags>(le)) {
781 type = lexrc.getString();
782 if (floatlist_.typeExist(type)) {
783 Floating const & fl = floatlist_.getType(type);
784 placement = fl.placement();
786 within = fl.within();
789 listName = fl.listName();
790 builtin = fl.builtin();
795 name = lexrc.getString();
799 placement = lexrc.getString();
803 ext = lexrc.getString();
807 within = lexrc.getString();
808 if (within == "none")
813 style = lexrc.getString();
817 listName = lexrc.getString();
821 builtin = lexrc.getBool();
829 // Here if have a full float if getout == true
831 Floating fl(type, placement, ext, within,
832 style, name, listName, builtin);
833 floatlist_.newFloat(fl);
834 // each float has its own counter
835 counters_.newCounter(from_ascii(type), from_ascii(within),
836 docstring(), docstring());
837 // also define sub-float counters
838 docstring const subtype = "sub-" + from_ascii(type);
839 counters_.newCounter(subtype, from_ascii(type),
840 "\\alph{" + subtype + "}", docstring());
851 CT_LABELSTRING_APPENDIX,
856 void TextClass::readCounter(Lexer & lexrc)
858 keyword_item counterTags[] = {
860 { "labelstring", CT_LABELSTRING },
861 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
863 { "within", CT_WITHIN }
866 lexrc.pushTable(counterTags, CT_END);
870 docstring labelstring;
871 docstring labelstring_appendix;
874 while (!getout && lexrc.isOK()) {
875 int le = lexrc.lex();
877 case Lexer::LEX_UNDEF:
878 lexrc.printError("Unknown counter tag `$$Token'");
882 switch (static_cast<CounterTags>(le)) {
885 name = lexrc.getDocString();
886 if (counters_.hasCounter(name))
887 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
889 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
893 within = lexrc.getDocString();
894 if (within == "none")
899 labelstring = lexrc.getDocString();
900 labelstring_appendix = labelstring;
902 case CT_LABELSTRING_APPENDIX:
904 labelstring_appendix = lexrc.getDocString();
912 // Here if have a full counter if getout == true
914 counters_.newCounter(name, within,
915 labelstring, labelstring_appendix);
921 bool TextClass::hasLayout(docstring const & n) const
923 docstring const name = n.empty() ? defaultLayoutName() : n;
925 return find_if(layoutlist_.begin(), layoutlist_.end(),
926 LayoutNamesEqual(name))
927 != layoutlist_.end();
932 Layout const & TextClass::operator[](docstring const & name) const
934 BOOST_ASSERT(!name.empty());
937 find_if(begin(), end(), LayoutNamesEqual(name));
940 lyxerr << "We failed to find the layout '" << to_utf8(name)
941 << "' in the layout list. You MUST investigate!"
943 for (const_iterator cit = begin(); cit != end(); ++cit)
944 lyxerr << " " << to_utf8(cit->name()) << endl;
946 // we require the name to exist
954 Layout & TextClass::operator[](docstring const & name)
956 BOOST_ASSERT(!name.empty());
958 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
961 lyxerr << "We failed to find the layout '" << to_utf8(name)
962 << "' in the layout list. You MUST investigate!"
964 for (const_iterator cit = begin(); cit != end(); ++cit)
965 lyxerr << " " << to_utf8(cit->name()) << endl;
967 // we require the name to exist
975 bool TextClass::deleteLayout(docstring const & name)
977 if (name == defaultLayoutName() || name == emptyLayoutName())
980 LayoutList::iterator it =
981 remove_if(layoutlist_.begin(), layoutlist_.end(),
982 LayoutNamesEqual(name));
984 LayoutList::iterator end = layoutlist_.end();
985 bool const ret = (it != end);
986 layoutlist_.erase(it, end);
991 // Load textclass info if not loaded yet
992 bool TextClass::load(string const & path) const
997 // Read style-file, provided path is searched before the system ones
998 FileName layout_file;
1000 layout_file = FileName(addName(path, name_ + ".layout"));
1001 if (layout_file.empty() || !layout_file.exists())
1002 layout_file = libFileSearch("layouts", name_, "layout");
1003 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1006 lyxerr << "Error reading `"
1007 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1008 << "'\n(Check `" << name_
1009 << "')\nCheck your installation and "
1010 "try Options/Reconfigure..." << endl;
1017 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1020 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1021 while (!n.empty()) {
1022 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1023 if (cit != cen && cit->first == n)
1025 size_t i = n.find(':');
1026 if (i == string::npos)
1030 return empty_insetlayout_;
1034 docstring const & TextClass::defaultLayoutName() const
1036 // This really should come from the actual layout... (Lgb)
1037 return defaultlayout_;
1041 Layout const & TextClass::defaultLayout() const
1043 return operator[](defaultLayoutName());
1047 bool TextClass::isDefaultLayout(Layout const & lay) const
1049 return lay.name() == defaultLayoutName();
1053 bool TextClass::isEmptyLayout(Layout const & lay) const
1055 return lay.name() == emptyLayoutName();
1059 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1061 DocumentClass * dc = new DocumentClass(baseClass);
1062 tc_list_.push_back(dc);
1063 return *tc_list_.back();
1067 DocumentClassBundle & DocumentClassBundle::get()
1069 static DocumentClassBundle singleton;
1074 DocumentClass::DocumentClass(LayoutFile const & tc)
1079 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1081 LayoutList::const_iterator it = layoutlist_.begin();
1082 LayoutList::const_iterator end = layoutlist_.end();
1083 for (; it != end; ++it)
1084 if (it->latexname() == lay)
1090 bool DocumentClass::provides(string const & p) const
1092 return provides_.find(p) != provides_.end();
1096 bool DocumentClass::hasTocLevels() const
1098 return min_toclevel_ != Layout::NOT_IN_TOC;
1102 ostream & operator<<(ostream & os, PageSides p)