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)
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
192 LexerKeyword textClassTags[] = {
193 { "addtopreamble", TC_ADDTOPREAMBLE },
194 { "classoptions", TC_CLASSOPTIONS },
195 { "columns", TC_COLUMNS },
196 { "counter", TC_COUNTER },
197 { "defaultfont", TC_DEFAULTFONT },
198 { "defaultstyle", TC_DEFAULTSTYLE },
199 { "environment", TC_ENVIRONMENT },
200 { "float", TC_FLOAT },
201 { "format", TC_FORMAT },
202 { "input", TC_INPUT },
203 { "insetlayout", TC_INSETLAYOUT },
204 { "leftmargin", TC_LEFTMARGIN },
205 { "nofloat", TC_NOFLOAT },
206 { "nostyle", TC_NOSTYLE },
207 { "outputtype", TC_OUTPUTTYPE },
208 { "pagestyle", TC_PAGESTYLE },
209 { "preamble", TC_PREAMBLE },
210 { "provides", TC_PROVIDES },
211 { "requires", TC_REQUIRES },
212 { "rightmargin", TC_RIGHTMARGIN },
213 { "secnumdepth", TC_SECNUMDEPTH },
214 { "sides", TC_SIDES },
215 { "style", TC_STYLE },
216 { "titlelatexname", TC_TITLELATEXNAME },
217 { "titlelatextype", TC_TITLELATEXTYPE },
218 { "tocdepth", TC_TOCDEPTH }
224 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
226 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
227 FileName const tempfile = FileName::tempName();
228 bool success = layout2layout(filename, tempfile);
230 success = read(tempfile, rt);
231 tempfile.removeFile();
235 bool TextClass::read(FileName const & filename, ReadType rt)
237 if (!filename.isReadableFile()) {
238 lyxerr << "Cannot read layout file `" << filename << "'."
243 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
244 to_utf8(makeDisplayPath(filename.absFilename())));
246 // Define the `empty' layout used in table cells, ert, etc. Note that
247 // we do this before loading any layout file, so that classes can
248 // override features of this layout if they should choose to do so.
249 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
250 static char const * s = "Margin Static\n"
251 "LatexType Paragraph\n"
254 "AlignPossible Left, Right, Center\n"
255 "LabelType No_Label\n"
258 Lexer lex(textClassTags);
261 lay.setName(emptylayout_);
262 if (!readStyle(lex, lay)) {
263 // The only way this happens is because the hardcoded layout above
265 LASSERT(false, /**/);
267 layoutlist_.push_back(lay);
270 Lexer lexrc(textClassTags);
271 lexrc.setFile(filename);
272 ReturnValues retval = read(lexrc, rt);
274 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
275 to_utf8(makeDisplayPath(filename.absFilename())));
277 if (retval != FORMAT_MISMATCH)
280 bool const worx = convertLayoutFormat(filename, rt);
282 lyxerr << "Unable to convert " << filename <<
283 " to format " << FORMAT << std::endl;
290 bool TextClass::validate(std::string const & str)
293 return tc.read(str, VALIDATION);
297 bool TextClass::read(std::string const & str, ReadType rt)
299 Lexer lexrc(textClassTags);
300 istringstream is(str);
302 ReturnValues retval = read(lexrc, rt);
304 if (retval != FORMAT_MISMATCH)
307 // write the layout string to a temporary file
308 FileName const tempfile = FileName::tempName();
309 ofstream os(tempfile.toFilesystemEncoding().c_str());
311 LYXERR0("Unable to create tempoary file");
317 // now try to convert it
318 bool const worx = convertLayoutFormat(tempfile, rt);
320 LYXERR0("Unable to convert internal layout information to format "
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);
407 layout.setName(name);
408 if (le == TC_ENVIRONMENT)
409 layout.is_environment = true;
410 error = !readStyle(lexrc, layout);
412 layoutlist_.push_back(layout);
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, layout);
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();
531 insetlayoutlist_[il.name()] = il;
532 // else there was an error, so forget it
544 case TC_TITLELATEXTYPE:
545 readTitleType(lexrc);
548 case TC_TITLELATEXNAME:
550 titlename_ = lexrc.getString();
555 string const nofloat = lexrc.getString();
556 floatlist_.erase(nofloat);
561 //Note that this is triggered the first time through the loop unless
562 //we hit a format tag.
563 if (format != FORMAT)
567 if (format != FORMAT)
568 return FORMAT_MISMATCH;
571 return (error ? ERROR : OK);
573 if (defaultlayout_.empty()) {
574 LYXERR0("Error: Textclass '" << name_
575 << "' is missing a defaultstyle.");
579 // Try to erase "stdinsets" from the provides_ set.
581 // Provides stdinsets 1
582 // declaration simply tells us that the standard insets have been
583 // defined. (It's found in stdinsets.inc but could also be used in
584 // user-defined files.) There isn't really any such package. So we
585 // might as well go ahead and erase it.
586 // If we do not succeed, then it was not there, which means that
587 // the textclass did not provide the definitions of the standard
588 // insets. So we need to try to load them.
589 int erased = provides_.erase("stdinsets");
591 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
594 throw ExceptionMessage(WarningException, _("Missing File"),
595 _("Could not find stdinsets.inc! This may lead to data loss!"));
597 } else if (!read(tmp, MERGE)) {
598 throw ExceptionMessage(WarningException, _("Corrupt File"),
599 _("Could not read stdinsets.inc! This may lead to data loss!"));
604 min_toclevel_ = Layout::NOT_IN_TOC;
605 max_toclevel_ = Layout::NOT_IN_TOC;
606 const_iterator lit = begin();
607 const_iterator len = end();
608 for (; lit != len; ++lit) {
609 int const toclevel = lit->toclevel;
610 if (toclevel != Layout::NOT_IN_TOC) {
611 if (min_toclevel_ == Layout::NOT_IN_TOC)
612 min_toclevel_ = toclevel;
614 min_toclevel_ = min(min_toclevel_, toclevel);
615 max_toclevel_ = max(max_toclevel_, toclevel);
618 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
619 << ", maximum is " << max_toclevel_);
621 return (error ? ERROR : OK);
625 void TextClass::readTitleType(Lexer & lexrc)
627 LexerKeyword titleTypeTags[] = {
628 { "commandafter", TITLE_COMMAND_AFTER },
629 { "environment", TITLE_ENVIRONMENT }
632 PushPopHelper pph(lexrc, titleTypeTags);
634 int le = lexrc.lex();
636 case Lexer::LEX_UNDEF:
637 lexrc.printError("Unknown output type `$$Token'");
639 case TITLE_COMMAND_AFTER:
640 case TITLE_ENVIRONMENT:
641 titletype_ = static_cast<TitleLatexType>(le);
644 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
650 void TextClass::readOutputType(Lexer & lexrc)
652 LexerKeyword outputTypeTags[] = {
653 { "docbook", DOCBOOK },
655 { "literate", LITERATE }
658 PushPopHelper pph(lexrc, outputTypeTags);
660 int le = lexrc.lex();
662 case Lexer::LEX_UNDEF:
663 lexrc.printError("Unknown output type `$$Token'");
668 outputType_ = static_cast<OutputType>(le);
671 LYXERR0("Unhandled value " << le);
677 void TextClass::readClassOptions(Lexer & lexrc)
687 LexerKeyword classOptionsTags[] = {
689 {"fontsize", CO_FONTSIZE },
690 {"header", CO_HEADER },
691 {"other", CO_OTHER },
692 {"pagestyle", CO_PAGESTYLE }
695 lexrc.pushTable(classOptionsTags);
697 while (!getout && lexrc.isOK()) {
698 int le = lexrc.lex();
700 case Lexer::LEX_UNDEF:
701 lexrc.printError("Unknown ClassOption tag `$$Token'");
708 opt_fontsize_ = rtrim(lexrc.getString());
712 opt_pagestyle_ = rtrim(lexrc.getString());
716 options_ = lexrc.getString();
720 class_header_ = subst(lexrc.getString(), """, "\"");
731 void TextClass::readFloat(Lexer & lexrc)
745 LexerKeyword floatTags[] = {
747 { "extension", FT_EXT },
748 { "guiname", FT_NAME },
749 { "latexbuiltin", FT_BUILTIN },
750 { "listname", FT_LISTNAME },
751 { "numberwithin", FT_WITHIN },
752 { "placement", FT_PLACEMENT },
753 { "style", FT_STYLE },
757 lexrc.pushTable(floatTags);
766 bool builtin = false;
769 while (!getout && lexrc.isOK()) {
770 int le = lexrc.lex();
772 case Lexer::LEX_UNDEF:
773 lexrc.printError("Unknown float tag `$$Token'");
780 type = lexrc.getString();
781 if (floatlist_.typeExist(type)) {
782 Floating const & fl = floatlist_.getType(type);
783 placement = fl.placement();
785 within = fl.within();
788 listName = fl.listName();
789 builtin = fl.builtin();
794 name = lexrc.getString();
798 placement = lexrc.getString();
802 ext = lexrc.getString();
806 within = lexrc.getString();
807 if (within == "none")
812 style = lexrc.getString();
816 listName = lexrc.getString();
820 builtin = lexrc.getBool();
828 // Here if have a full float if getout == true
830 Floating fl(type, placement, ext, within,
831 style, name, listName, builtin);
832 floatlist_.newFloat(fl);
833 // each float has its own counter
834 counters_.newCounter(from_ascii(type), from_ascii(within),
835 docstring(), docstring());
836 // also define sub-float counters
837 docstring const subtype = "sub-" + from_ascii(type);
838 counters_.newCounter(subtype, from_ascii(type),
839 "\\alph{" + subtype + "}", docstring());
846 void TextClass::readCounter(Lexer & lexrc)
852 CT_LABELSTRING_APPENDIX,
856 LexerKeyword counterTags[] = {
858 { "labelstring", CT_LABELSTRING },
859 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
861 { "within", CT_WITHIN }
864 lexrc.pushTable(counterTags);
868 docstring labelstring;
869 docstring labelstring_appendix;
872 while (!getout && lexrc.isOK()) {
873 int le = lexrc.lex();
875 case Lexer::LEX_UNDEF:
876 lexrc.printError("Unknown counter tag `$$Token'");
883 name = lexrc.getDocString();
884 if (counters_.hasCounter(name))
885 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
887 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
891 within = lexrc.getDocString();
892 if (within == "none")
897 labelstring = lexrc.getDocString();
898 labelstring_appendix = labelstring;
900 case CT_LABELSTRING_APPENDIX:
902 labelstring_appendix = lexrc.getDocString();
910 // Here if have a full counter if getout == true
912 counters_.newCounter(name, within,
913 labelstring, labelstring_appendix);
919 bool TextClass::hasLayout(docstring const & n) const
921 docstring const name = n.empty() ? defaultLayoutName() : n;
923 return find_if(layoutlist_.begin(), layoutlist_.end(),
924 LayoutNamesEqual(name))
925 != layoutlist_.end();
930 Layout const & TextClass::operator[](docstring const & name) const
932 LASSERT(!name.empty(), /**/);
935 find_if(begin(), end(), LayoutNamesEqual(name));
938 lyxerr << "We failed to find the layout '" << to_utf8(name)
939 << "' in the layout list. You MUST investigate!"
941 for (const_iterator cit = begin(); cit != end(); ++cit)
942 lyxerr << " " << to_utf8(cit->name()) << endl;
944 // we require the name to exist
945 LASSERT(false, /**/);
952 Layout & TextClass::operator[](docstring const & name)
954 LASSERT(!name.empty(), /**/);
956 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
959 LYXERR0("We failed to find the layout '" << to_utf8(name)
960 << "' in the layout list. You MUST investigate!");
961 for (const_iterator cit = begin(); cit != end(); ++cit)
962 LYXERR0(" " << to_utf8(cit->name()));
964 // we require the name to exist
965 LASSERT(false, /**/);
972 bool TextClass::deleteLayout(docstring const & name)
974 if (name == defaultLayoutName() || name == emptyLayoutName())
977 LayoutList::iterator it =
978 remove_if(layoutlist_.begin(), layoutlist_.end(),
979 LayoutNamesEqual(name));
981 LayoutList::iterator end = layoutlist_.end();
982 bool const ret = (it != end);
983 layoutlist_.erase(it, end);
988 // Load textclass info if not loaded yet
989 bool TextClass::load(string const & path) const
994 // Read style-file, provided path is searched before the system ones
995 FileName layout_file;
997 layout_file = FileName(addName(path, name_ + ".layout"));
998 if (layout_file.empty() || !layout_file.exists())
999 layout_file = libFileSearch("layouts", name_, "layout");
1000 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1003 lyxerr << "Error reading `"
1004 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1005 << "'\n(Check `" << name_
1006 << "')\nCheck your installation and "
1007 "try Options/Reconfigure..." << endl;
1014 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1017 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1018 while (!n.empty()) {
1019 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1020 if (cit != cen && cit->first == n)
1022 size_t i = n.find(':');
1023 if (i == string::npos)
1027 return empty_insetlayout_;
1031 docstring const & TextClass::defaultLayoutName() const
1033 // This really should come from the actual layout... (Lgb)
1034 return defaultlayout_;
1038 Layout const & TextClass::defaultLayout() const
1040 return operator[](defaultLayoutName());
1044 bool TextClass::isDefaultLayout(Layout const & layout) const
1046 return layout.name() == defaultLayoutName();
1050 bool TextClass::isEmptyLayout(Layout const & layout) const
1052 return layout.name() == emptyLayoutName();
1056 /////////////////////////////////////////////////////////////////////////
1058 // DocumentClassBundle
1060 /////////////////////////////////////////////////////////////////////////
1062 DocumentClassBundle::~DocumentClassBundle()
1064 for (size_t i = 0; i != documentClasses_.size(); ++i)
1065 delete documentClasses_[i];
1066 documentClasses_.clear();
1069 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1071 DocumentClass * dc = new DocumentClass(baseClass);
1072 documentClasses_.push_back(dc);
1073 return *documentClasses_.back();
1077 DocumentClassBundle & DocumentClassBundle::get()
1079 static DocumentClassBundle singleton;
1084 /////////////////////////////////////////////////////////////////////////
1088 /////////////////////////////////////////////////////////////////////////
1090 DocumentClass::DocumentClass(LayoutFile const & tc)
1095 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1097 LayoutList::const_iterator it = layoutlist_.begin();
1098 LayoutList::const_iterator end = layoutlist_.end();
1099 for (; it != end; ++it)
1100 if (it->latexname() == lay)
1106 bool DocumentClass::provides(string const & p) const
1108 return provides_.find(p) != provides_.end();
1112 bool DocumentClass::hasTocLevels() const
1114 return min_toclevel_ != Layout::NOT_IN_TOC;
1118 /////////////////////////////////////////////////////////////////////////
1122 /////////////////////////////////////////////////////////////////////////
1124 ostream & operator<<(ostream & os, PageSides p)