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 keyword_item 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, sizeof(textClassTags) / sizeof(textClassTags[0]));
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);
263 Lexer lexrc(textClassTags,
264 sizeof(textClassTags) / sizeof(textClassTags[0]));
266 lexrc.setFile(filename);
267 ReturnValues retval = read(lexrc, rt);
269 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
270 to_utf8(makeDisplayPath(filename.absFilename())));
272 if (retval != FORMAT_MISMATCH)
275 bool const worx = convertLayoutFormat(filename, rt);
277 lyxerr << "Unable to convert " << filename <<
278 " to format " << FORMAT << std::endl;
285 bool TextClass::validate(std::string const & str)
288 return tc.read(str, VALIDATION);
292 bool TextClass::read(std::string const & str, ReadType rt)
294 Lexer lexrc(textClassTags,
295 sizeof(textClassTags) / sizeof(textClassTags[0]));
296 istringstream is(str);
298 ReturnValues retval = read(lexrc, rt);
300 if (retval != FORMAT_MISMATCH)
303 // write the layout string to a temporary file
304 FileName const tempfile = FileName::tempName();
305 ofstream os(tempfile.toFilesystemEncoding().c_str());
307 lyxerr << "Unable to create tempoary file in TextClass::read!!"
314 // now try to convert it
315 bool const worx = convertLayoutFormat(tempfile, rt);
317 lyxerr << "Unable to convert internal layout information to format "
318 << FORMAT << std::endl;
320 tempfile.removeFile();
325 // Reads a textclass structure from file.
326 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
328 bool error = !lexrc.isOK();
330 // Format of files before the 'Format' tag was introduced
334 while (lexrc.isOK() && !error) {
335 int le = lexrc.lex();
338 case Lexer::LEX_FEOF:
341 case Lexer::LEX_UNDEF:
342 lexrc.printError("Unknown TextClass tag `$$Token'");
350 switch (static_cast<TextClassTags>(le)) {
354 format = lexrc.getInteger();
357 case TC_OUTPUTTYPE: // output type definition
358 readOutputType(lexrc);
361 case TC_INPUT: // Include file
363 string const inc = lexrc.getString();
364 FileName tmp = libFileSearch("layouts", inc,
368 lexrc.printError("Could not find input file: " + inc);
370 } else if (!read(tmp, MERGE)) {
371 lexrc.printError("Error reading input"
372 "file: " + tmp.absFilename());
378 case TC_DEFAULTSTYLE:
380 docstring const name = from_utf8(subst(lexrc.getString(),
382 defaultlayout_ = name;
389 docstring const name = from_utf8(subst(lexrc.getString(),
392 string s = "Could not read name for style: `$$Token' "
393 + lexrc.getString() + " is probably not valid UTF-8!";
394 lexrc.printError(s.c_str());
396 // Since we couldn't read the name, we just scan the rest
397 // of the style and discard it.
398 error = !readStyle(lexrc, lay);
399 } else if (hasLayout(name)) {
400 Layout & lay = operator[](name);
401 error = !readStyle(lexrc, lay);
405 if (le == TC_ENVIRONMENT)
406 lay.is_environment = true;
407 error = !readStyle(lexrc, lay);
409 layoutlist_.push_back(lay);
411 if (defaultlayout_.empty()) {
412 // We do not have a default layout yet, so we choose
413 // the first layout we encounter.
414 defaultlayout_ = name;
419 //FIXME Should we also eat the style here? viz:
421 //readStyle(lexrc, lay);
423 lexrc.printError("No name given for style: `$$Token'.");
430 docstring const style = from_utf8(subst(lexrc.getString(),
432 if (!deleteLayout(style))
433 lyxerr << "Cannot delete style `"
434 << to_utf8(style) << '\'' << endl;
440 columns_ = lexrc.getInteger();
445 switch (lexrc.getInteger()) {
446 case 1: sides_ = OneSide; break;
447 case 2: sides_ = TwoSides; break;
449 lyxerr << "Impossible number of page"
450 " sides, setting to one."
460 pagestyle_ = rtrim(lexrc.getString());
464 defaultfont_ = lyxRead(lexrc);
465 if (!defaultfont_.resolved()) {
466 lexrc.printError("Warning: defaultfont should "
467 "be fully instantiated!");
468 defaultfont_.realize(sane_font);
474 secnumdepth_ = lexrc.getInteger();
479 tocdepth_ = lexrc.getInteger();
482 // First step to support options
483 case TC_CLASSOPTIONS:
484 readClassOptions(lexrc);
488 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
491 case TC_ADDTOPREAMBLE:
492 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
497 string const feature = lexrc.getString();
499 if (lexrc.getInteger())
500 provides_.insert(feature);
502 provides_.erase(feature);
508 vector<string> const req
509 = getVectorFromString(lexrc.getString());
510 requires_.insert(req.begin(), req.end());
514 case TC_LEFTMARGIN: // left margin type
516 leftmargin_ = lexrc.getDocString();
519 case TC_RIGHTMARGIN: // right margin type
521 rightmargin_ = lexrc.getDocString();
527 if (il.read(lexrc)) {
528 insetlayoutlist_[il.name()] = il;
530 // else there was an error, so forget it
542 case TC_TITLELATEXTYPE:
543 readTitleType(lexrc);
546 case TC_TITLELATEXNAME:
548 titlename_ = lexrc.getString();
553 string const nofloat = lexrc.getString();
554 floatlist_.erase(nofloat);
559 //Note that this is triggered the first time through the loop unless
560 //we hit a format tag.
561 if (format != FORMAT)
565 if (format != FORMAT)
566 return FORMAT_MISMATCH;
569 return (error ? ERROR : OK);
571 if (defaultlayout_.empty()) {
572 lyxerr << "Error: Textclass '" << name_
573 << "' is missing a defaultstyle." << endl;
577 //Try to erase "stdinsets" from the provides_ set.
579 // Provides stdinsets 1
580 //declaration simply tells us that the standard insets have been
581 //defined. (It's found in stdinsets.inc but could also be used in
582 //user-defined files.) There isn't really any such package. So we
583 //might as well go ahead and erase it.
584 //If we do not succeed, then it was not there, which means that
585 //the textclass did not provide the definitions of the standard
586 //insets. So we need to try to load them.
587 int erased = provides_.erase("stdinsets");
589 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
592 throw ExceptionMessage(WarningException, _("Missing File"),
593 _("Could not find stdinsets.inc! This may lead to data loss!"));
595 } else if (!read(tmp, MERGE)) {
596 throw ExceptionMessage(WarningException, _("Corrupt File"),
597 _("Could not read stdinsets.inc! This may lead to data loss!"));
602 min_toclevel_ = Layout::NOT_IN_TOC;
603 max_toclevel_ = Layout::NOT_IN_TOC;
604 const_iterator lit = begin();
605 const_iterator len = end();
606 for (; lit != len; ++lit) {
607 int const toclevel = lit->toclevel;
608 if (toclevel != Layout::NOT_IN_TOC) {
609 if (min_toclevel_ == Layout::NOT_IN_TOC)
610 min_toclevel_ = toclevel;
612 min_toclevel_ = min(min_toclevel_, toclevel);
613 max_toclevel_ = max(max_toclevel_, toclevel);
616 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
617 << ", maximum is " << max_toclevel_);
619 return (error ? ERROR : OK);
623 void TextClass::readTitleType(Lexer & lexrc)
625 keyword_item titleTypeTags[] = {
626 { "commandafter", TITLE_COMMAND_AFTER },
627 { "environment", TITLE_ENVIRONMENT }
630 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
632 int le = lexrc.lex();
634 case Lexer::LEX_UNDEF:
635 lexrc.printError("Unknown output type `$$Token'");
637 case TITLE_COMMAND_AFTER:
638 case TITLE_ENVIRONMENT:
639 titletype_ = static_cast<TitleLatexType>(le);
642 lyxerr << "Unhandled value " << le
643 << " in TextClass::readTitleType." << endl;
650 void TextClass::readOutputType(Lexer & lexrc)
652 keyword_item outputTypeTags[] = {
653 { "docbook", DOCBOOK },
655 { "literate", LITERATE }
658 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
660 int le = lexrc.lex();
662 case Lexer::LEX_UNDEF:
663 lexrc.printError("Unknown output type `$$Token'");
668 outputType_ = static_cast<OutputType>(le);
671 lyxerr << "Unhandled value " << le
672 << " in TextClass::readOutputType." << endl;
679 enum ClassOptionsTags {
688 void TextClass::readClassOptions(Lexer & lexrc)
690 keyword_item classOptionsTags[] = {
692 {"fontsize", CO_FONTSIZE },
693 {"header", CO_HEADER },
694 {"other", CO_OTHER },
695 {"pagestyle", CO_PAGESTYLE }
698 lexrc.pushTable(classOptionsTags, CO_END);
700 while (!getout && lexrc.isOK()) {
701 int le = lexrc.lex();
703 case Lexer::LEX_UNDEF:
704 lexrc.printError("Unknown ClassOption tag `$$Token'");
708 switch (static_cast<ClassOptionsTags>(le)) {
711 opt_fontsize_ = rtrim(lexrc.getString());
715 opt_pagestyle_ = rtrim(lexrc.getString());
719 options_ = lexrc.getString();
723 class_header_ = subst(lexrc.getString(), """, "\"");
747 void TextClass::readFloat(Lexer & lexrc)
749 keyword_item floatTags[] = {
751 { "extension", FT_EXT },
752 { "guiname", FT_NAME },
753 { "latexbuiltin", FT_BUILTIN },
754 { "listname", FT_LISTNAME },
755 { "numberwithin", FT_WITHIN },
756 { "placement", FT_PLACEMENT },
757 { "style", FT_STYLE },
761 lexrc.pushTable(floatTags, FT_END);
770 bool builtin = false;
773 while (!getout && lexrc.isOK()) {
774 int le = lexrc.lex();
776 case Lexer::LEX_UNDEF:
777 lexrc.printError("Unknown float tag `$$Token'");
781 switch (static_cast<FloatTags>(le)) {
784 type = lexrc.getString();
785 if (floatlist_.typeExist(type)) {
786 Floating const & fl = floatlist_.getType(type);
787 placement = fl.placement();
789 within = fl.within();
792 listName = fl.listName();
793 builtin = fl.builtin();
798 name = lexrc.getString();
802 placement = lexrc.getString();
806 ext = lexrc.getString();
810 within = lexrc.getString();
811 if (within == "none")
816 style = lexrc.getString();
820 listName = lexrc.getString();
824 builtin = lexrc.getBool();
832 // Here if have a full float if getout == true
834 Floating fl(type, placement, ext, within,
835 style, name, listName, builtin);
836 floatlist_.newFloat(fl);
837 // each float has its own counter
838 counters_.newCounter(from_ascii(type), from_ascii(within),
839 docstring(), docstring());
840 // also define sub-float counters
841 docstring const subtype = "sub-" + from_ascii(type);
842 counters_.newCounter(subtype, from_ascii(type),
843 "\\alph{" + subtype + "}", docstring());
854 CT_LABELSTRING_APPENDIX,
859 void TextClass::readCounter(Lexer & lexrc)
861 keyword_item counterTags[] = {
863 { "labelstring", CT_LABELSTRING },
864 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
866 { "within", CT_WITHIN }
869 lexrc.pushTable(counterTags, CT_END);
873 docstring labelstring;
874 docstring labelstring_appendix;
877 while (!getout && lexrc.isOK()) {
878 int le = lexrc.lex();
880 case Lexer::LEX_UNDEF:
881 lexrc.printError("Unknown counter tag `$$Token'");
885 switch (static_cast<CounterTags>(le)) {
888 name = lexrc.getDocString();
889 if (counters_.hasCounter(name))
890 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
892 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
896 within = lexrc.getDocString();
897 if (within == "none")
902 labelstring = lexrc.getDocString();
903 labelstring_appendix = labelstring;
905 case CT_LABELSTRING_APPENDIX:
907 labelstring_appendix = lexrc.getDocString();
915 // Here if have a full counter if getout == true
917 counters_.newCounter(name, within,
918 labelstring, labelstring_appendix);
924 bool TextClass::hasLayout(docstring const & n) const
926 docstring const name = n.empty() ? defaultLayoutName() : n;
928 return find_if(layoutlist_.begin(), layoutlist_.end(),
929 LayoutNamesEqual(name))
930 != layoutlist_.end();
935 Layout const & TextClass::operator[](docstring const & name) const
937 BOOST_ASSERT(!name.empty());
940 find_if(begin(), end(), LayoutNamesEqual(name));
943 lyxerr << "We failed to find the layout '" << to_utf8(name)
944 << "' in the layout list. You MUST investigate!"
946 for (const_iterator cit = begin(); cit != end(); ++cit)
947 lyxerr << " " << to_utf8(cit->name()) << endl;
949 // we require the name to exist
957 Layout & TextClass::operator[](docstring const & name)
959 BOOST_ASSERT(!name.empty());
961 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
964 lyxerr << "We failed to find the layout '" << to_utf8(name)
965 << "' in the layout list. You MUST investigate!"
967 for (const_iterator cit = begin(); cit != end(); ++cit)
968 lyxerr << " " << to_utf8(cit->name()) << endl;
970 // we require the name to exist
978 bool TextClass::deleteLayout(docstring const & name)
980 if (name == defaultLayoutName() || name == emptyLayoutName())
983 LayoutList::iterator it =
984 remove_if(layoutlist_.begin(), layoutlist_.end(),
985 LayoutNamesEqual(name));
987 LayoutList::iterator end = layoutlist_.end();
988 bool const ret = (it != end);
989 layoutlist_.erase(it, end);
994 // Load textclass info if not loaded yet
995 bool TextClass::load(string const & path) const
1000 // Read style-file, provided path is searched before the system ones
1001 FileName layout_file;
1003 layout_file = FileName(addName(path, name_ + ".layout"));
1004 if (layout_file.empty() || !layout_file.exists())
1005 layout_file = libFileSearch("layouts", name_, "layout");
1006 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1009 lyxerr << "Error reading `"
1010 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1011 << "'\n(Check `" << name_
1012 << "')\nCheck your installation and "
1013 "try Options/Reconfigure..." << endl;
1020 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1023 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1024 while (!n.empty()) {
1025 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1026 if (cit != cen && cit->first == n)
1028 size_t i = n.find(':');
1029 if (i == string::npos)
1033 return empty_insetlayout_;
1037 docstring const & TextClass::defaultLayoutName() const
1039 // This really should come from the actual layout... (Lgb)
1040 return defaultlayout_;
1044 Layout const & TextClass::defaultLayout() const
1046 return operator[](defaultLayoutName());
1050 bool TextClass::isDefaultLayout(Layout const & lay) const
1052 return lay.name() == defaultLayoutName();
1056 bool TextClass::isEmptyLayout(Layout const & lay) const
1058 return lay.name() == emptyLayoutName();
1062 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1064 DocumentClass * dc = new DocumentClass(baseClass);
1065 tc_list_.push_back(dc);
1066 return *tc_list_.back();
1070 DocumentClassBundle & DocumentClassBundle::get()
1072 static DocumentClassBundle singleton;
1077 DocumentClass::DocumentClass(LayoutFile const & tc)
1082 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1084 LayoutList::const_iterator it = layoutlist_.begin();
1085 LayoutList::const_iterator end = layoutlist_.end();
1086 for (; it != end; ++it)
1087 if (it->latexname() == lay)
1093 bool DocumentClass::provides(string const & p) const
1095 return provides_.find(p) != provides_.end();
1099 bool DocumentClass::hasTocLevels() const
1101 return min_toclevel_ != Layout::NOT_IN_TOC;
1105 ostream & operator<<(ostream & os, PageSides p)