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(N_("Plain Layout"));
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";
138 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
140 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
141 if (!lay.read(lexrc, *this)) {
142 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
146 lay.resfont = lay.font;
147 lay.resfont.realize(defaultfont_);
148 lay.reslabelfont = lay.labelfont;
149 lay.reslabelfont.realize(defaultfont_);
150 return true; // no errors
186 LexerKeyword textClassTags[] = {
187 { "addtopreamble", TC_ADDTOPREAMBLE },
188 { "classoptions", TC_CLASSOPTIONS },
189 { "columns", TC_COLUMNS },
190 { "counter", TC_COUNTER },
191 { "defaultfont", TC_DEFAULTFONT },
192 { "defaultstyle", TC_DEFAULTSTYLE },
193 { "environment", TC_ENVIRONMENT },
194 { "float", TC_FLOAT },
195 { "format", TC_FORMAT },
196 { "input", TC_INPUT },
197 { "insetlayout", TC_INSETLAYOUT },
198 { "leftmargin", TC_LEFTMARGIN },
199 { "nofloat", TC_NOFLOAT },
200 { "nostyle", TC_NOSTYLE },
201 { "outputtype", TC_OUTPUTTYPE },
202 { "pagestyle", TC_PAGESTYLE },
203 { "preamble", TC_PREAMBLE },
204 { "provides", TC_PROVIDES },
205 { "requires", TC_REQUIRES },
206 { "rightmargin", TC_RIGHTMARGIN },
207 { "secnumdepth", TC_SECNUMDEPTH },
208 { "sides", TC_SIDES },
209 { "style", TC_STYLE },
210 { "titlelatexname", TC_TITLELATEXNAME },
211 { "titlelatextype", TC_TITLELATEXTYPE },
212 { "tocdepth", TC_TOCDEPTH }
218 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
220 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
221 FileName const tempfile = FileName::tempName();
222 bool success = layout2layout(filename, tempfile);
224 success = read(tempfile, rt);
225 tempfile.removeFile();
229 bool TextClass::read(FileName const & filename, ReadType rt)
231 if (!filename.isReadableFile()) {
232 lyxerr << "Cannot read layout file `" << filename << "'."
237 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
238 to_utf8(makeDisplayPath(filename.absFilename())));
240 // Define the `empty' layout used in table cells, ert, etc. Note that
241 // we do this before loading any layout file, so that classes can
242 // override features of this layout if they should choose to do so.
243 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
244 static char const * s = "Margin Static\n"
245 "LatexType Paragraph\n"
248 "AlignPossible Left, Right, Center\n"
249 "LabelType No_Label\n"
252 Lexer lex(textClassTags);
255 lay.setName(emptylayout_);
256 if (!readStyle(lex, lay)) {
257 // The only way this happens is because the hardcoded layout above
261 layoutlist_.push_back(lay);
264 Lexer lexrc(textClassTags);
265 lexrc.setFile(filename);
266 ReturnValues retval = read(lexrc, rt);
268 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
269 to_utf8(makeDisplayPath(filename.absFilename())));
271 if (retval != FORMAT_MISMATCH)
274 bool const worx = convertLayoutFormat(filename, rt);
276 lyxerr << "Unable to convert " << filename <<
277 " to format " << FORMAT << std::endl;
284 bool TextClass::validate(std::string const & str)
287 return tc.read(str, VALIDATION);
291 bool TextClass::read(std::string const & str, ReadType rt)
293 Lexer lexrc(textClassTags);
294 istringstream is(str);
296 ReturnValues retval = read(lexrc, rt);
298 if (retval != FORMAT_MISMATCH)
301 // write the layout string to a temporary file
302 FileName const tempfile = FileName::tempName();
303 ofstream os(tempfile.toFilesystemEncoding().c_str());
305 lyxerr << "Unable to create tempoary file in TextClass::read!!"
312 // now try to convert it
313 bool const worx = convertLayoutFormat(tempfile, rt);
315 lyxerr << "Unable to convert internal layout information to format "
316 << FORMAT << std::endl;
318 tempfile.removeFile();
323 // Reads a textclass structure from file.
324 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
326 bool error = !lexrc.isOK();
328 // Format of files before the 'Format' tag was introduced
332 while (lexrc.isOK() && !error) {
333 int le = lexrc.lex();
336 case Lexer::LEX_FEOF:
339 case Lexer::LEX_UNDEF:
340 lexrc.printError("Unknown TextClass tag `$$Token'");
348 switch (static_cast<TextClassTags>(le)) {
352 format = lexrc.getInteger();
355 case TC_OUTPUTTYPE: // output type definition
356 readOutputType(lexrc);
359 case TC_INPUT: // Include file
361 string const inc = lexrc.getString();
362 FileName tmp = libFileSearch("layouts", inc,
366 lexrc.printError("Could not find input file: " + inc);
368 } else if (!read(tmp, MERGE)) {
369 lexrc.printError("Error reading input"
370 "file: " + tmp.absFilename());
376 case TC_DEFAULTSTYLE:
378 docstring const name = from_utf8(subst(lexrc.getString(),
380 defaultlayout_ = name;
387 docstring const name = from_utf8(subst(lexrc.getString(),
390 string s = "Could not read name for style: `$$Token' "
391 + lexrc.getString() + " is probably not valid UTF-8!";
392 lexrc.printError(s.c_str());
394 // Since we couldn't read the name, we just scan the rest
395 // of the style and discard it.
396 error = !readStyle(lexrc, lay);
397 } else if (hasLayout(name)) {
398 Layout & lay = operator[](name);
399 error = !readStyle(lexrc, lay);
403 if (le == TC_ENVIRONMENT)
404 lay.is_environment = true;
405 error = !readStyle(lexrc, lay);
407 layoutlist_.push_back(lay);
409 if (defaultlayout_.empty()) {
410 // We do not have a default layout yet, so we choose
411 // the first layout we encounter.
412 defaultlayout_ = name;
417 //FIXME Should we also eat the style here? viz:
419 //readStyle(lexrc, lay);
421 lexrc.printError("No name given for style: `$$Token'.");
428 docstring const style = from_utf8(subst(lexrc.getString(),
430 if (!deleteLayout(style))
431 lyxerr << "Cannot delete style `"
432 << to_utf8(style) << '\'' << endl;
438 columns_ = lexrc.getInteger();
443 switch (lexrc.getInteger()) {
444 case 1: sides_ = OneSide; break;
445 case 2: sides_ = TwoSides; break;
447 lyxerr << "Impossible number of page"
448 " sides, setting to one."
458 pagestyle_ = rtrim(lexrc.getString());
462 defaultfont_ = lyxRead(lexrc);
463 if (!defaultfont_.resolved()) {
464 lexrc.printError("Warning: defaultfont should "
465 "be fully instantiated!");
466 defaultfont_.realize(sane_font);
472 secnumdepth_ = lexrc.getInteger();
477 tocdepth_ = lexrc.getInteger();
480 // First step to support options
481 case TC_CLASSOPTIONS:
482 readClassOptions(lexrc);
486 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
489 case TC_ADDTOPREAMBLE:
490 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
495 string const feature = lexrc.getString();
497 if (lexrc.getInteger())
498 provides_.insert(feature);
500 provides_.erase(feature);
506 vector<string> const req
507 = getVectorFromString(lexrc.getString());
508 requires_.insert(req.begin(), req.end());
512 case TC_LEFTMARGIN: // left margin type
514 leftmargin_ = lexrc.getDocString();
517 case TC_RIGHTMARGIN: // right margin type
519 rightmargin_ = lexrc.getDocString();
525 if (il.read(lexrc)) {
526 insetlayoutlist_[il.name()] = il;
528 // else there was an error, so forget it
540 case TC_TITLELATEXTYPE:
541 readTitleType(lexrc);
544 case TC_TITLELATEXNAME:
546 titlename_ = lexrc.getString();
551 string const nofloat = lexrc.getString();
552 floatlist_.erase(nofloat);
557 //Note that this is triggered the first time through the loop unless
558 //we hit a format tag.
559 if (format != FORMAT)
563 if (format != FORMAT)
564 return FORMAT_MISMATCH;
567 return (error ? ERROR : OK);
569 if (defaultlayout_.empty()) {
570 lyxerr << "Error: Textclass '" << name_
571 << "' is missing a defaultstyle." << endl;
575 //Try to erase "stdinsets" from the provides_ set.
577 // Provides stdinsets 1
578 //declaration simply tells us that the standard insets have been
579 //defined. (It's found in stdinsets.inc but could also be used in
580 //user-defined files.) There isn't really any such package. So we
581 //might as well go ahead and erase it.
582 //If we do not succeed, then it was not there, which means that
583 //the textclass did not provide the definitions of the standard
584 //insets. So we need to try to load them.
585 int erased = provides_.erase("stdinsets");
587 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
590 throw ExceptionMessage(WarningException, _("Missing File"),
591 _("Could not find stdinsets.inc! This may lead to data loss!"));
593 } else if (!read(tmp, MERGE)) {
594 throw ExceptionMessage(WarningException, _("Corrupt File"),
595 _("Could not read stdinsets.inc! This may lead to data loss!"));
600 min_toclevel_ = Layout::NOT_IN_TOC;
601 max_toclevel_ = Layout::NOT_IN_TOC;
602 const_iterator lit = begin();
603 const_iterator len = end();
604 for (; lit != len; ++lit) {
605 int const toclevel = lit->toclevel;
606 if (toclevel != Layout::NOT_IN_TOC) {
607 if (min_toclevel_ == Layout::NOT_IN_TOC)
608 min_toclevel_ = toclevel;
610 min_toclevel_ = min(min_toclevel_, toclevel);
611 max_toclevel_ = max(max_toclevel_, toclevel);
614 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
615 << ", maximum is " << max_toclevel_);
617 return (error ? ERROR : OK);
621 void TextClass::readTitleType(Lexer & lexrc)
623 LexerKeyword titleTypeTags[] = {
624 { "commandafter", TITLE_COMMAND_AFTER },
625 { "environment", TITLE_ENVIRONMENT }
628 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
630 int le = lexrc.lex();
632 case Lexer::LEX_UNDEF:
633 lexrc.printError("Unknown output type `$$Token'");
635 case TITLE_COMMAND_AFTER:
636 case TITLE_ENVIRONMENT:
637 titletype_ = static_cast<TitleLatexType>(le);
640 lyxerr << "Unhandled value " << le
641 << " in TextClass::readTitleType." << endl;
648 void TextClass::readOutputType(Lexer & lexrc)
650 LexerKeyword outputTypeTags[] = {
651 { "docbook", DOCBOOK },
653 { "literate", LITERATE }
656 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
658 int le = lexrc.lex();
660 case Lexer::LEX_UNDEF:
661 lexrc.printError("Unknown output type `$$Token'");
666 outputType_ = static_cast<OutputType>(le);
669 lyxerr << "Unhandled value " << le
670 << " in TextClass::readOutputType." << endl;
677 enum ClassOptionsTags {
686 void TextClass::readClassOptions(Lexer & lexrc)
688 LexerKeyword classOptionsTags[] = {
690 {"fontsize", CO_FONTSIZE },
691 {"header", CO_HEADER },
692 {"other", CO_OTHER },
693 {"pagestyle", CO_PAGESTYLE }
696 lexrc.pushTable(classOptionsTags);
698 while (!getout && lexrc.isOK()) {
699 int le = lexrc.lex();
701 case Lexer::LEX_UNDEF:
702 lexrc.printError("Unknown ClassOption tag `$$Token'");
706 switch (static_cast<ClassOptionsTags>(le)) {
709 opt_fontsize_ = rtrim(lexrc.getString());
713 opt_pagestyle_ = rtrim(lexrc.getString());
717 options_ = lexrc.getString();
721 class_header_ = subst(lexrc.getString(), """, "\"");
745 void TextClass::readFloat(Lexer & lexrc)
747 LexerKeyword floatTags[] = {
749 { "extension", FT_EXT },
750 { "guiname", FT_NAME },
751 { "latexbuiltin", FT_BUILTIN },
752 { "listname", FT_LISTNAME },
753 { "numberwithin", FT_WITHIN },
754 { "placement", FT_PLACEMENT },
755 { "style", FT_STYLE },
759 lexrc.pushTable(floatTags);
768 bool builtin = false;
771 while (!getout && lexrc.isOK()) {
772 int le = lexrc.lex();
774 case Lexer::LEX_UNDEF:
775 lexrc.printError("Unknown float tag `$$Token'");
779 switch (static_cast<FloatTags>(le)) {
782 type = lexrc.getString();
783 if (floatlist_.typeExist(type)) {
784 Floating const & fl = floatlist_.getType(type);
785 placement = fl.placement();
787 within = fl.within();
790 listName = fl.listName();
791 builtin = fl.builtin();
796 name = lexrc.getString();
800 placement = lexrc.getString();
804 ext = lexrc.getString();
808 within = lexrc.getString();
809 if (within == "none")
814 style = lexrc.getString();
818 listName = lexrc.getString();
822 builtin = lexrc.getBool();
830 // Here if have a full float if getout == true
832 Floating fl(type, placement, ext, within,
833 style, name, listName, builtin);
834 floatlist_.newFloat(fl);
835 // each float has its own counter
836 counters_.newCounter(from_ascii(type), from_ascii(within),
837 docstring(), docstring());
838 // also define sub-float counters
839 docstring const subtype = "sub-" + from_ascii(type);
840 counters_.newCounter(subtype, from_ascii(type),
841 "\\alph{" + subtype + "}", docstring());
852 CT_LABELSTRING_APPENDIX,
857 void TextClass::readCounter(Lexer & lexrc)
859 LexerKeyword counterTags[] = {
861 { "labelstring", CT_LABELSTRING },
862 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
864 { "within", CT_WITHIN }
867 lexrc.pushTable(counterTags);
871 docstring labelstring;
872 docstring labelstring_appendix;
875 while (!getout && lexrc.isOK()) {
876 int le = lexrc.lex();
878 case Lexer::LEX_UNDEF:
879 lexrc.printError("Unknown counter tag `$$Token'");
883 switch (static_cast<CounterTags>(le)) {
886 name = lexrc.getDocString();
887 if (counters_.hasCounter(name))
888 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
890 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
894 within = lexrc.getDocString();
895 if (within == "none")
900 labelstring = lexrc.getDocString();
901 labelstring_appendix = labelstring;
903 case CT_LABELSTRING_APPENDIX:
905 labelstring_appendix = lexrc.getDocString();
913 // Here if have a full counter if getout == true
915 counters_.newCounter(name, within,
916 labelstring, labelstring_appendix);
922 bool TextClass::hasLayout(docstring const & n) const
924 docstring const name = n.empty() ? defaultLayoutName() : n;
926 return find_if(layoutlist_.begin(), layoutlist_.end(),
927 LayoutNamesEqual(name))
928 != layoutlist_.end();
933 Layout const & TextClass::operator[](docstring const & name) const
935 BOOST_ASSERT(!name.empty());
938 find_if(begin(), end(), LayoutNamesEqual(name));
941 lyxerr << "We failed to find the layout '" << to_utf8(name)
942 << "' in the layout list. You MUST investigate!"
944 for (const_iterator cit = begin(); cit != end(); ++cit)
945 lyxerr << " " << to_utf8(cit->name()) << endl;
947 // we require the name to exist
955 Layout & TextClass::operator[](docstring const & name)
957 BOOST_ASSERT(!name.empty());
959 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
962 lyxerr << "We failed to find the layout '" << to_utf8(name)
963 << "' in the layout list. You MUST investigate!"
965 for (const_iterator cit = begin(); cit != end(); ++cit)
966 lyxerr << " " << to_utf8(cit->name()) << endl;
968 // we require the name to exist
976 bool TextClass::deleteLayout(docstring const & name)
978 if (name == defaultLayoutName() || name == emptyLayoutName())
981 LayoutList::iterator it =
982 remove_if(layoutlist_.begin(), layoutlist_.end(),
983 LayoutNamesEqual(name));
985 LayoutList::iterator end = layoutlist_.end();
986 bool const ret = (it != end);
987 layoutlist_.erase(it, end);
992 // Load textclass info if not loaded yet
993 bool TextClass::load(string const & path) const
998 // Read style-file, provided path is searched before the system ones
999 FileName layout_file;
1001 layout_file = FileName(addName(path, name_ + ".layout"));
1002 if (layout_file.empty() || !layout_file.exists())
1003 layout_file = libFileSearch("layouts", name_, "layout");
1004 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1007 lyxerr << "Error reading `"
1008 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1009 << "'\n(Check `" << name_
1010 << "')\nCheck your installation and "
1011 "try Options/Reconfigure..." << endl;
1018 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1021 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1022 while (!n.empty()) {
1023 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1024 if (cit != cen && cit->first == n)
1026 size_t i = n.find(':');
1027 if (i == string::npos)
1031 return empty_insetlayout_;
1035 docstring const & TextClass::defaultLayoutName() const
1037 // This really should come from the actual layout... (Lgb)
1038 return defaultlayout_;
1042 Layout const & TextClass::defaultLayout() const
1044 return operator[](defaultLayoutName());
1048 bool TextClass::isDefaultLayout(Layout const & lay) const
1050 return lay.name() == defaultLayoutName();
1054 bool TextClass::isEmptyLayout(Layout const & lay) const
1056 return lay.name() == emptyLayoutName();
1060 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1062 DocumentClass * dc = new DocumentClass(baseClass);
1063 tc_list_.push_back(dc);
1064 return *tc_list_.back();
1068 DocumentClassBundle & DocumentClassBundle::get()
1070 static DocumentClassBundle singleton;
1075 DocumentClass::DocumentClass(LayoutFile const & tc)
1080 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1082 LayoutList::const_iterator it = layoutlist_.begin();
1083 LayoutList::const_iterator end = layoutlist_.end();
1084 for (; it != end; ++it)
1085 if (it->latexname() == lay)
1091 bool DocumentClass::provides(string const & p) const
1093 return provides_.find(p) != provides_.end();
1097 bool DocumentClass::hasTocLevels() const
1099 return min_toclevel_ != Layout::NOT_IN_TOC;
1103 ostream & operator<<(ostream & os, PageSides p)