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);
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);
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 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 BOOST_ASSERT(!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
952 Layout & TextClass::operator[](docstring const & name)
954 BOOST_ASSERT(!name.empty());
956 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
959 lyxerr << "We failed to find the layout '" << to_utf8(name)
960 << "' in the layout list. You MUST investigate!"
962 for (const_iterator cit = begin(); cit != end(); ++cit)
963 lyxerr << " " << to_utf8(cit->name()) << endl;
965 // we require the name to exist
973 bool TextClass::deleteLayout(docstring const & name)
975 if (name == defaultLayoutName() || name == emptyLayoutName())
978 LayoutList::iterator it =
979 remove_if(layoutlist_.begin(), layoutlist_.end(),
980 LayoutNamesEqual(name));
982 LayoutList::iterator end = layoutlist_.end();
983 bool const ret = (it != end);
984 layoutlist_.erase(it, end);
989 // Load textclass info if not loaded yet
990 bool TextClass::load(string const & path) const
995 // Read style-file, provided path is searched before the system ones
996 FileName layout_file;
998 layout_file = FileName(addName(path, name_ + ".layout"));
999 if (layout_file.empty() || !layout_file.exists())
1000 layout_file = libFileSearch("layouts", name_, "layout");
1001 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
1004 lyxerr << "Error reading `"
1005 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1006 << "'\n(Check `" << name_
1007 << "')\nCheck your installation and "
1008 "try Options/Reconfigure..." << endl;
1015 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1018 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1019 while (!n.empty()) {
1020 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1021 if (cit != cen && cit->first == n)
1023 size_t i = n.find(':');
1024 if (i == string::npos)
1028 return empty_insetlayout_;
1032 docstring const & TextClass::defaultLayoutName() const
1034 // This really should come from the actual layout... (Lgb)
1035 return defaultlayout_;
1039 Layout const & TextClass::defaultLayout() const
1041 return operator[](defaultLayoutName());
1045 bool TextClass::isDefaultLayout(Layout const & lay) const
1047 return lay.name() == defaultLayoutName();
1051 bool TextClass::isEmptyLayout(Layout const & lay) const
1053 return lay.name() == emptyLayoutName();
1057 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1059 DocumentClass * dc = new DocumentClass(baseClass);
1060 tc_list_.push_back(dc);
1061 return *tc_list_.back();
1065 DocumentClassBundle & DocumentClassBundle::get()
1067 static DocumentClassBundle singleton;
1072 DocumentClass::DocumentClass(LayoutFile const & tc)
1077 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1079 LayoutList::const_iterator it = layoutlist_.begin();
1080 LayoutList::const_iterator end = layoutlist_.end();
1081 for (; it != end; ++it)
1082 if (it->latexname() == lay)
1088 bool DocumentClass::provides(string const & p) const
1090 return provides_.find(p) != provides_.end();
1094 bool DocumentClass::hasTocLevels() const
1096 return min_toclevel_ != Layout::NOT_IN_TOC;
1100 ostream & operator<<(ostream & os, PageSides p)