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
189 keyword_item textClassTags[] = {
190 { "addtopreamble", TC_ADDTOPREAMBLE },
191 { "classoptions", TC_CLASSOPTIONS },
192 { "columns", TC_COLUMNS },
193 { "counter", TC_COUNTER },
194 { "defaultfont", TC_DEFAULTFONT },
195 { "defaultstyle", TC_DEFAULTSTYLE },
196 { "environment", TC_ENVIRONMENT },
197 { "float", TC_FLOAT },
198 { "format", TC_FORMAT },
199 { "input", TC_INPUT },
200 { "insetlayout", TC_INSETLAYOUT },
201 { "leftmargin", TC_LEFTMARGIN },
202 { "nofloat", TC_NOFLOAT },
203 { "nostyle", TC_NOSTYLE },
204 { "outputtype", TC_OUTPUTTYPE },
205 { "pagestyle", TC_PAGESTYLE },
206 { "preamble", TC_PREAMBLE },
207 { "provides", TC_PROVIDES },
208 { "requires", TC_REQUIRES },
209 { "rightmargin", TC_RIGHTMARGIN },
210 { "secnumdepth", TC_SECNUMDEPTH },
211 { "sides", TC_SIDES },
212 { "style", TC_STYLE },
213 { "titlelatexname", TC_TITLELATEXNAME },
214 { "titlelatextype", TC_TITLELATEXTYPE },
215 { "tocdepth", TC_TOCDEPTH }
221 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
223 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
224 FileName const tempfile = FileName::tempName();
225 bool success = layout2layout(filename, tempfile);
227 success = read(tempfile, rt);
228 tempfile.removeFile();
232 bool TextClass::read(FileName const & filename, ReadType rt)
234 if (!filename.isReadableFile()) {
235 lyxerr << "Cannot read layout file `" << filename << "'."
240 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
241 to_utf8(makeDisplayPath(filename.absFilename())));
243 // Define the `empty' layout used in table cells, ert, etc. Note that
244 // we do this before loading any layout file, so that classes can
245 // override features of this layout if they should choose to do so.
246 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
247 static char const * s = "Margin Static\n"
248 "LatexType Paragraph\n"
251 "AlignPossible Left, Right, Center\n"
252 "LabelType No_Label\n"
255 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
258 lay.setName(emptylayout_);
259 if (!readStyle(lex, lay)) {
260 // The only way this happens is because the hardcoded layout above
264 layoutlist_.push_back(lay);
266 Lexer lexrc(textClassTags,
267 sizeof(textClassTags) / sizeof(textClassTags[0]));
269 lexrc.setFile(filename);
270 ReturnValues retval = read(lexrc, rt);
272 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
273 to_utf8(makeDisplayPath(filename.absFilename())));
275 if (retval != FORMAT_MISMATCH)
278 bool const worx = convertLayoutFormat(filename, rt);
280 lyxerr << "Unable to convert " << filename <<
281 " to format " << FORMAT << std::endl;
288 bool TextClass::validate(std::string const & str)
291 return tc.read(str, VALIDATION);
295 bool TextClass::read(std::string const & str, ReadType rt)
297 Lexer lexrc(textClassTags,
298 sizeof(textClassTags) / sizeof(textClassTags[0]));
299 istringstream is(str);
301 ReturnValues retval = read(lexrc, rt);
303 if (retval != FORMAT_MISMATCH)
306 // write the layout string to a temporary file
307 FileName const tempfile = FileName::tempName();
308 ofstream os(tempfile.toFilesystemEncoding().c_str());
310 lyxerr << "Unable to create tempoary file in TextClass::read!!"
317 // now try to convert it
318 bool const worx = convertLayoutFormat(tempfile, rt);
320 lyxerr << "Unable to convert internal layout information to format "
321 << FORMAT << std::endl;
323 tempfile.removeFile();
328 // Reads a textclass structure from file.
329 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
331 bool error = !lexrc.isOK();
333 // Format of files before the 'Format' tag was introduced
337 while (lexrc.isOK() && !error) {
338 int le = lexrc.lex();
341 case Lexer::LEX_FEOF:
344 case Lexer::LEX_UNDEF:
345 lexrc.printError("Unknown TextClass tag `$$Token'");
353 switch (static_cast<TextClassTags>(le)) {
357 format = lexrc.getInteger();
360 case TC_OUTPUTTYPE: // output type definition
361 readOutputType(lexrc);
364 case TC_INPUT: // Include file
366 string const inc = lexrc.getString();
367 FileName tmp = libFileSearch("layouts", inc,
371 lexrc.printError("Could not find input file: " + inc);
373 } else if (!read(tmp, MERGE)) {
374 lexrc.printError("Error reading input"
375 "file: " + tmp.absFilename());
381 case TC_DEFAULTSTYLE:
383 docstring const name = from_utf8(subst(lexrc.getString(),
385 defaultlayout_ = name;
392 docstring const name = from_utf8(subst(lexrc.getString(),
395 string s = "Could not read name for style: `$$Token' "
396 + lexrc.getString() + " is probably not valid UTF-8!";
397 lexrc.printError(s.c_str());
399 // Since we couldn't read the name, we just scan the rest
400 // of the style and discard it.
401 error = !readStyle(lexrc, lay);
402 } else if (hasLayout(name)) {
403 Layout & lay = operator[](name);
404 error = !readStyle(lexrc, lay);
408 if (le == TC_ENVIRONMENT)
409 lay.is_environment = true;
410 error = !readStyle(lexrc, lay);
412 layoutlist_.push_back(lay);
414 if (defaultlayout_.empty()) {
415 // We do not have a default layout yet, so we choose
416 // the first layout we encounter.
417 defaultlayout_ = name;
422 //FIXME Should we also eat the style here? viz:
424 //readStyle(lexrc, lay);
426 lexrc.printError("No name given for style: `$$Token'.");
433 docstring const style = from_utf8(subst(lexrc.getString(),
435 if (!deleteLayout(style))
436 lyxerr << "Cannot delete style `"
437 << to_utf8(style) << '\'' << endl;
443 columns_ = lexrc.getInteger();
448 switch (lexrc.getInteger()) {
449 case 1: sides_ = OneSide; break;
450 case 2: sides_ = TwoSides; break;
452 lyxerr << "Impossible number of page"
453 " sides, setting to one."
463 pagestyle_ = rtrim(lexrc.getString());
467 defaultfont_ = lyxRead(lexrc);
468 if (!defaultfont_.resolved()) {
469 lexrc.printError("Warning: defaultfont should "
470 "be fully instantiated!");
471 defaultfont_.realize(sane_font);
477 secnumdepth_ = lexrc.getInteger();
482 tocdepth_ = lexrc.getInteger();
485 // First step to support options
486 case TC_CLASSOPTIONS:
487 readClassOptions(lexrc);
491 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
494 case TC_ADDTOPREAMBLE:
495 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
500 string const feature = lexrc.getString();
502 if (lexrc.getInteger())
503 provides_.insert(feature);
505 provides_.erase(feature);
511 vector<string> const req
512 = getVectorFromString(lexrc.getString());
513 requires_.insert(req.begin(), req.end());
517 case TC_LEFTMARGIN: // left margin type
519 leftmargin_ = lexrc.getDocString();
522 case TC_RIGHTMARGIN: // right margin type
524 rightmargin_ = lexrc.getDocString();
530 if (il.read(lexrc)) {
531 insetlayoutlist_[il.name()] = il;
533 // else there was an error, so forget it
545 case TC_TITLELATEXTYPE:
546 readTitleType(lexrc);
549 case TC_TITLELATEXNAME:
551 titlename_ = lexrc.getString();
556 string const nofloat = lexrc.getString();
557 floatlist_.erase(nofloat);
562 //Note that this is triggered the first time through the loop unless
563 //we hit a format tag.
564 if (format != FORMAT)
568 if (format != FORMAT)
569 return FORMAT_MISMATCH;
572 return (error ? ERROR : OK);
574 if (defaultlayout_.empty()) {
575 lyxerr << "Error: Textclass '" << name_
576 << "' is missing a defaultstyle." << endl;
580 //Try to erase "stdinsets" from the provides_ set.
582 // Provides stdinsets 1
583 //declaration simply tells us that the standard insets have been
584 //defined. (It's found in stdinsets.inc but could also be used in
585 //user-defined files.) There isn't really any such package. So we
586 //might as well go ahead and erase it.
587 //If we do not succeed, then it was not there, which means that
588 //the textclass did not provide the definitions of the standard
589 //insets. So we need to try to load them.
590 int erased = provides_.erase("stdinsets");
592 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
595 throw ExceptionMessage(WarningException, _("Missing File"),
596 _("Could not find stdinsets.inc! This may lead to data loss!"));
598 } else if (!read(tmp, MERGE)) {
599 throw ExceptionMessage(WarningException, _("Corrupt File"),
600 _("Could not read stdinsets.inc! This may lead to data loss!"));
605 min_toclevel_ = Layout::NOT_IN_TOC;
606 max_toclevel_ = Layout::NOT_IN_TOC;
607 const_iterator lit = begin();
608 const_iterator len = end();
609 for (; lit != len; ++lit) {
610 int const toclevel = lit->toclevel;
611 if (toclevel != Layout::NOT_IN_TOC) {
612 if (min_toclevel_ == Layout::NOT_IN_TOC)
613 min_toclevel_ = toclevel;
615 min_toclevel_ = min(min_toclevel_, toclevel);
616 max_toclevel_ = max(max_toclevel_, toclevel);
619 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
620 << ", maximum is " << max_toclevel_);
622 return (error ? ERROR : OK);
626 void TextClass::readTitleType(Lexer & lexrc)
628 keyword_item titleTypeTags[] = {
629 { "commandafter", TITLE_COMMAND_AFTER },
630 { "environment", TITLE_ENVIRONMENT }
633 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
635 int le = lexrc.lex();
637 case Lexer::LEX_UNDEF:
638 lexrc.printError("Unknown output type `$$Token'");
640 case TITLE_COMMAND_AFTER:
641 case TITLE_ENVIRONMENT:
642 titletype_ = static_cast<TitleLatexType>(le);
645 lyxerr << "Unhandled value " << le
646 << " in TextClass::readTitleType." << endl;
653 void TextClass::readOutputType(Lexer & lexrc)
655 keyword_item outputTypeTags[] = {
656 { "docbook", DOCBOOK },
658 { "literate", LITERATE }
661 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
663 int le = lexrc.lex();
665 case Lexer::LEX_UNDEF:
666 lexrc.printError("Unknown output type `$$Token'");
671 outputType_ = static_cast<OutputType>(le);
674 lyxerr << "Unhandled value " << le
675 << " in TextClass::readOutputType." << endl;
682 enum ClassOptionsTags {
691 void TextClass::readClassOptions(Lexer & lexrc)
693 keyword_item classOptionsTags[] = {
695 {"fontsize", CO_FONTSIZE },
696 {"header", CO_HEADER },
697 {"other", CO_OTHER },
698 {"pagestyle", CO_PAGESTYLE }
701 lexrc.pushTable(classOptionsTags, CO_END);
703 while (!getout && lexrc.isOK()) {
704 int le = lexrc.lex();
706 case Lexer::LEX_UNDEF:
707 lexrc.printError("Unknown ClassOption tag `$$Token'");
711 switch (static_cast<ClassOptionsTags>(le)) {
714 opt_fontsize_ = rtrim(lexrc.getString());
718 opt_pagestyle_ = rtrim(lexrc.getString());
722 options_ = lexrc.getString();
726 class_header_ = subst(lexrc.getString(), """, "\"");
750 void TextClass::readFloat(Lexer & lexrc)
752 keyword_item floatTags[] = {
754 { "extension", FT_EXT },
755 { "guiname", FT_NAME },
756 { "latexbuiltin", FT_BUILTIN },
757 { "listname", FT_LISTNAME },
758 { "numberwithin", FT_WITHIN },
759 { "placement", FT_PLACEMENT },
760 { "style", FT_STYLE },
764 lexrc.pushTable(floatTags, FT_END);
773 bool builtin = false;
776 while (!getout && lexrc.isOK()) {
777 int le = lexrc.lex();
779 case Lexer::LEX_UNDEF:
780 lexrc.printError("Unknown float tag `$$Token'");
784 switch (static_cast<FloatTags>(le)) {
787 type = lexrc.getString();
788 if (floatlist_.typeExist(type)) {
789 Floating const & fl = floatlist_.getType(type);
790 placement = fl.placement();
792 within = fl.within();
795 listName = fl.listName();
796 builtin = fl.builtin();
801 name = lexrc.getString();
805 placement = lexrc.getString();
809 ext = lexrc.getString();
813 within = lexrc.getString();
814 if (within == "none")
819 style = lexrc.getString();
823 listName = lexrc.getString();
827 builtin = lexrc.getBool();
835 // Here if have a full float if getout == true
837 Floating fl(type, placement, ext, within,
838 style, name, listName, builtin);
839 floatlist_.newFloat(fl);
840 // each float has its own counter
841 counters_.newCounter(from_ascii(type), from_ascii(within),
842 docstring(), docstring());
843 // also define sub-float counters
844 docstring const subtype = "sub-" + from_ascii(type);
845 counters_.newCounter(subtype, from_ascii(type),
846 "\\alph{" + subtype + "}", docstring());
857 CT_LABELSTRING_APPENDIX,
862 void TextClass::readCounter(Lexer & lexrc)
864 keyword_item counterTags[] = {
866 { "labelstring", CT_LABELSTRING },
867 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
869 { "within", CT_WITHIN }
872 lexrc.pushTable(counterTags, CT_END);
876 docstring labelstring;
877 docstring labelstring_appendix;
880 while (!getout && lexrc.isOK()) {
881 int le = lexrc.lex();
883 case Lexer::LEX_UNDEF:
884 lexrc.printError("Unknown counter tag `$$Token'");
888 switch (static_cast<CounterTags>(le)) {
891 name = lexrc.getDocString();
892 if (counters_.hasCounter(name))
893 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
895 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
899 within = lexrc.getDocString();
900 if (within == "none")
905 labelstring = lexrc.getDocString();
906 labelstring_appendix = labelstring;
908 case CT_LABELSTRING_APPENDIX:
910 labelstring_appendix = lexrc.getDocString();
918 // Here if have a full counter if getout == true
920 counters_.newCounter(name, within,
921 labelstring, labelstring_appendix);
927 bool TextClass::hasLayout(docstring const & n) const
929 docstring const name = n.empty() ? defaultLayoutName() : n;
931 return find_if(layoutlist_.begin(), layoutlist_.end(),
932 LayoutNamesEqual(name))
933 != layoutlist_.end();
938 Layout const & TextClass::operator[](docstring const & name) const
940 BOOST_ASSERT(!name.empty());
943 find_if(begin(), end(), LayoutNamesEqual(name));
946 lyxerr << "We failed to find the layout '" << to_utf8(name)
947 << "' in the layout list. You MUST investigate!"
949 for (const_iterator cit = begin(); cit != end(); ++cit)
950 lyxerr << " " << to_utf8(cit->name()) << endl;
952 // we require the name to exist
960 Layout & TextClass::operator[](docstring const & name)
962 BOOST_ASSERT(!name.empty());
964 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
967 lyxerr << "We failed to find the layout '" << to_utf8(name)
968 << "' in the layout list. You MUST investigate!"
970 for (const_iterator cit = begin(); cit != end(); ++cit)
971 lyxerr << " " << to_utf8(cit->name()) << endl;
973 // we require the name to exist
981 bool TextClass::deleteLayout(docstring const & name)
983 if (name == defaultLayoutName() || name == emptyLayoutName())
986 LayoutList::iterator it =
987 remove_if(layoutlist_.begin(), layoutlist_.end(),
988 LayoutNamesEqual(name));
990 LayoutList::iterator end = layoutlist_.end();
991 bool const ret = (it != end);
992 layoutlist_.erase(it, end);
997 // Load textclass info if not loaded yet
998 bool TextClass::load(string const & path) const
1003 // Read style-file, provided path is searched before the system ones
1004 FileName layout_file;
1006 layout_file = FileName(addName(path, name_ + ".layout"));
1007 if (layout_file.empty() || !layout_file.exists())
1008 layout_file = libFileSearch("layouts", name_, "layout");
1009 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1012 lyxerr << "Error reading `"
1013 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1014 << "'\n(Check `" << name_
1015 << "')\nCheck your installation and "
1016 "try Options/Reconfigure..." << endl;
1023 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1026 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1027 while (!n.empty()) {
1028 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1029 if (cit != cen && cit->first == n)
1031 size_t i = n.find(':');
1032 if (i == string::npos)
1036 return empty_insetlayout_;
1040 docstring const & TextClass::defaultLayoutName() const
1042 // This really should come from the actual layout... (Lgb)
1043 return defaultlayout_;
1047 Layout const & TextClass::defaultLayout() const
1049 return operator[](defaultLayoutName());
1053 bool TextClass::isDefaultLayout(Layout const & lay) const
1055 return lay.name() == defaultLayoutName();
1059 bool TextClass::isEmptyLayout(Layout const & lay) const
1061 return lay.name() == emptyLayoutName();
1065 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1067 DocumentClass * dc = new DocumentClass(baseClass);
1068 tc_list_.push_back(dc);
1069 return *tc_list_.back();
1073 DocumentClassBundle & DocumentClassBundle::get()
1075 static DocumentClassBundle singleton;
1080 DocumentClass::DocumentClass(LayoutFile const & tc)
1085 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1087 LayoutList::const_iterator it = layoutlist_.begin();
1088 LayoutList::const_iterator end = layoutlist_.end();
1089 for (; it != end; ++it)
1090 if (it->latexname() == lay)
1096 bool DocumentClass::provides(string const & p) const
1098 return provides_.find(p) != provides_.end();
1102 bool DocumentClass::hasTocLevels() const
1104 return min_toclevel_ != Layout::NOT_IN_TOC;
1108 ostream & operator<<(ostream & os, PageSides p)