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
191 LexerKeyword textClassTags[] = {
192 { "addtopreamble", TC_ADDTOPREAMBLE },
193 { "classoptions", TC_CLASSOPTIONS },
194 { "columns", TC_COLUMNS },
195 { "counter", TC_COUNTER },
196 { "defaultfont", TC_DEFAULTFONT },
197 { "defaultstyle", TC_DEFAULTSTYLE },
198 { "float", TC_FLOAT },
199 { "format", TC_FORMAT },
200 { "input", TC_INPUT },
201 { "insetlayout", TC_INSETLAYOUT },
202 { "leftmargin", TC_LEFTMARGIN },
203 { "nofloat", TC_NOFLOAT },
204 { "nostyle", TC_NOSTYLE },
205 { "outputtype", TC_OUTPUTTYPE },
206 { "pagestyle", TC_PAGESTYLE },
207 { "preamble", TC_PREAMBLE },
208 { "provides", TC_PROVIDES },
209 { "requires", TC_REQUIRES },
210 { "rightmargin", TC_RIGHTMARGIN },
211 { "secnumdepth", TC_SECNUMDEPTH },
212 { "sides", TC_SIDES },
213 { "style", TC_STYLE },
214 { "titlelatexname", TC_TITLELATEXNAME },
215 { "titlelatextype", TC_TITLELATEXTYPE },
216 { "tocdepth", TC_TOCDEPTH }
222 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
224 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
225 FileName const tempfile = FileName::tempName();
226 bool success = layout2layout(filename, tempfile);
228 success = read(tempfile, rt);
229 tempfile.removeFile();
233 bool TextClass::read(FileName const & filename, ReadType rt)
235 if (!filename.isReadableFile()) {
236 lyxerr << "Cannot read layout file `" << filename << "'."
241 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
242 to_utf8(makeDisplayPath(filename.absFilename())));
244 // Define the `empty' layout used in table cells, ert, etc. Note that
245 // we do this before loading any layout file, so that classes can
246 // override features of this layout if they should choose to do so.
247 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
248 static char const * s = "Margin Static\n"
249 "LatexType Paragraph\n"
252 "AlignPossible Left, Right, Center\n"
253 "LabelType No_Label\n"
256 Lexer lex(textClassTags);
259 lay.setName(emptylayout_);
260 if (!readStyle(lex, lay)) {
261 // The only way this happens is because the hardcoded layout above
263 LASSERT(false, /**/);
265 layoutlist_.push_back(lay);
268 Lexer lexrc(textClassTags);
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 istringstream is(str);
300 ReturnValues retval = read(lexrc, rt);
302 if (retval != FORMAT_MISMATCH)
305 // write the layout string to a temporary file
306 FileName const tempfile = FileName::tempName();
307 ofstream os(tempfile.toFilesystemEncoding().c_str());
309 LYXERR0("Unable to create tempoary file");
315 // now try to convert it
316 bool const worx = convertLayoutFormat(tempfile, rt);
318 LYXERR0("Unable to convert internal layout information to format "
321 tempfile.removeFile();
326 // Reads a textclass structure from file.
327 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
329 bool error = !lexrc.isOK();
331 // Format of files before the 'Format' tag was introduced
335 while (lexrc.isOK() && !error) {
336 int le = lexrc.lex();
339 case Lexer::LEX_FEOF:
342 case Lexer::LEX_UNDEF:
343 lexrc.printError("Unknown TextClass tag `$$Token'");
351 switch (static_cast<TextClassTags>(le)) {
355 format = lexrc.getInteger();
358 case TC_OUTPUTTYPE: // output type definition
359 readOutputType(lexrc);
362 case TC_INPUT: // Include file
364 string const inc = lexrc.getString();
365 FileName tmp = libFileSearch("layouts", inc,
369 lexrc.printError("Could not find input file: " + inc);
371 } else if (!read(tmp, MERGE)) {
372 lexrc.printError("Error reading input"
373 "file: " + tmp.absFilename());
379 case TC_DEFAULTSTYLE:
381 docstring const name = from_utf8(subst(lexrc.getString(),
383 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);
404 layout.setName(name);
405 error = !readStyle(lexrc, layout);
407 layoutlist_.push_back(layout);
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, layout);
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();
526 insetlayoutlist_[il.name()] = il;
527 // else there was an error, so forget it
539 case TC_TITLELATEXTYPE:
540 readTitleType(lexrc);
543 case TC_TITLELATEXNAME:
545 titlename_ = lexrc.getString();
550 string const nofloat = lexrc.getString();
551 floatlist_.erase(nofloat);
556 //Note that this is triggered the first time through the loop unless
557 //we hit a format tag.
558 if (format != FORMAT)
562 if (format != FORMAT)
563 return FORMAT_MISMATCH;
566 return (error ? ERROR : OK);
568 if (defaultlayout_.empty()) {
569 LYXERR0("Error: Textclass '" << name_
570 << "' is missing a defaultstyle.");
574 // Try to erase "stdinsets" from the provides_ set.
576 // Provides stdinsets 1
577 // declaration simply tells us that the standard insets have been
578 // defined. (It's found in stdinsets.inc but could also be used in
579 // user-defined files.) There isn't really any such package. So we
580 // might as well go ahead and erase it.
581 // If we do not succeed, then it was not there, which means that
582 // the textclass did not provide the definitions of the standard
583 // insets. So we need to try to load them.
584 int erased = provides_.erase("stdinsets");
586 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
589 throw ExceptionMessage(WarningException, _("Missing File"),
590 _("Could not find stdinsets.inc! This may lead to data loss!"));
592 } else if (!read(tmp, MERGE)) {
593 throw ExceptionMessage(WarningException, _("Corrupt File"),
594 _("Could not read stdinsets.inc! This may lead to data loss!"));
599 min_toclevel_ = Layout::NOT_IN_TOC;
600 max_toclevel_ = Layout::NOT_IN_TOC;
601 const_iterator lit = begin();
602 const_iterator len = end();
603 for (; lit != len; ++lit) {
604 int const toclevel = lit->toclevel;
605 if (toclevel != Layout::NOT_IN_TOC) {
606 if (min_toclevel_ == Layout::NOT_IN_TOC)
607 min_toclevel_ = toclevel;
609 min_toclevel_ = min(min_toclevel_, toclevel);
610 max_toclevel_ = max(max_toclevel_, toclevel);
613 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
614 << ", maximum is " << max_toclevel_);
616 return (error ? ERROR : OK);
620 void TextClass::readTitleType(Lexer & lexrc)
622 LexerKeyword titleTypeTags[] = {
623 { "commandafter", TITLE_COMMAND_AFTER },
624 { "environment", TITLE_ENVIRONMENT }
627 PushPopHelper pph(lexrc, titleTypeTags);
629 int le = lexrc.lex();
631 case Lexer::LEX_UNDEF:
632 lexrc.printError("Unknown output type `$$Token'");
634 case TITLE_COMMAND_AFTER:
635 case TITLE_ENVIRONMENT:
636 titletype_ = static_cast<TitleLatexType>(le);
639 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
645 void TextClass::readOutputType(Lexer & lexrc)
647 LexerKeyword outputTypeTags[] = {
648 { "docbook", DOCBOOK },
650 { "literate", LITERATE }
653 PushPopHelper pph(lexrc, outputTypeTags);
655 int le = lexrc.lex();
657 case Lexer::LEX_UNDEF:
658 lexrc.printError("Unknown output type `$$Token'");
663 outputType_ = static_cast<OutputType>(le);
666 LYXERR0("Unhandled value " << le);
672 void TextClass::readClassOptions(Lexer & lexrc)
682 LexerKeyword classOptionsTags[] = {
684 {"fontsize", CO_FONTSIZE },
685 {"header", CO_HEADER },
686 {"other", CO_OTHER },
687 {"pagestyle", CO_PAGESTYLE }
690 lexrc.pushTable(classOptionsTags);
692 while (!getout && lexrc.isOK()) {
693 int le = lexrc.lex();
695 case Lexer::LEX_UNDEF:
696 lexrc.printError("Unknown ClassOption tag `$$Token'");
703 opt_fontsize_ = rtrim(lexrc.getString());
707 opt_pagestyle_ = rtrim(lexrc.getString());
711 options_ = lexrc.getString();
715 class_header_ = subst(lexrc.getString(), """, "\"");
726 void TextClass::readFloat(Lexer & lexrc)
740 LexerKeyword floatTags[] = {
742 { "extension", FT_EXT },
743 { "guiname", FT_NAME },
744 { "latexbuiltin", FT_BUILTIN },
745 { "listname", FT_LISTNAME },
746 { "numberwithin", FT_WITHIN },
747 { "placement", FT_PLACEMENT },
748 { "style", FT_STYLE },
752 lexrc.pushTable(floatTags);
761 bool builtin = false;
764 while (!getout && lexrc.isOK()) {
765 int le = lexrc.lex();
767 case Lexer::LEX_UNDEF:
768 lexrc.printError("Unknown float tag `$$Token'");
775 type = lexrc.getString();
776 if (floatlist_.typeExist(type)) {
777 Floating const & fl = floatlist_.getType(type);
778 placement = fl.placement();
780 within = fl.within();
783 listName = fl.listName();
784 builtin = fl.builtin();
789 name = lexrc.getString();
793 placement = lexrc.getString();
797 ext = lexrc.getString();
801 within = lexrc.getString();
802 if (within == "none")
807 style = lexrc.getString();
811 listName = lexrc.getString();
815 builtin = lexrc.getBool();
823 // Here if have a full float if getout == true
825 Floating fl(type, placement, ext, within,
826 style, name, listName, builtin);
827 floatlist_.newFloat(fl);
828 // each float has its own counter
829 counters_.newCounter(from_ascii(type), from_ascii(within),
830 docstring(), docstring());
831 // also define sub-float counters
832 docstring const subtype = "sub-" + from_ascii(type);
833 counters_.newCounter(subtype, from_ascii(type),
834 "\\alph{" + subtype + "}", docstring());
841 void TextClass::readCounter(Lexer & lexrc)
847 CT_LABELSTRING_APPENDIX,
851 LexerKeyword counterTags[] = {
853 { "labelstring", CT_LABELSTRING },
854 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
856 { "within", CT_WITHIN }
859 lexrc.pushTable(counterTags);
863 docstring labelstring;
864 docstring labelstring_appendix;
867 while (!getout && lexrc.isOK()) {
868 int le = lexrc.lex();
870 case Lexer::LEX_UNDEF:
871 lexrc.printError("Unknown counter tag `$$Token'");
878 name = lexrc.getDocString();
879 if (counters_.hasCounter(name))
880 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
882 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
886 within = lexrc.getDocString();
887 if (within == "none")
892 labelstring = lexrc.getDocString();
893 labelstring_appendix = labelstring;
895 case CT_LABELSTRING_APPENDIX:
897 labelstring_appendix = lexrc.getDocString();
905 // Here if have a full counter if getout == true
907 counters_.newCounter(name, within,
908 labelstring, labelstring_appendix);
914 bool TextClass::hasLayout(docstring const & n) const
916 docstring const name = n.empty() ? defaultLayoutName() : n;
918 return find_if(layoutlist_.begin(), layoutlist_.end(),
919 LayoutNamesEqual(name))
920 != layoutlist_.end();
925 Layout const & TextClass::operator[](docstring const & name) const
927 LASSERT(!name.empty(), /**/);
930 find_if(begin(), end(), LayoutNamesEqual(name));
933 lyxerr << "We failed to find the layout '" << to_utf8(name)
934 << "' in the layout list. You MUST investigate!"
936 for (const_iterator cit = begin(); cit != end(); ++cit)
937 lyxerr << " " << to_utf8(cit->name()) << endl;
939 // we require the name to exist
940 LASSERT(false, /**/);
947 Layout & TextClass::operator[](docstring const & name)
949 LASSERT(!name.empty(), /**/);
951 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
954 LYXERR0("We failed to find the layout '" << to_utf8(name)
955 << "' in the layout list. You MUST investigate!");
956 for (const_iterator cit = begin(); cit != end(); ++cit)
957 LYXERR0(" " << to_utf8(cit->name()));
959 // we require the name to exist
960 LASSERT(false, /**/);
967 bool TextClass::deleteLayout(docstring const & name)
969 if (name == defaultLayoutName() || name == emptyLayoutName())
972 LayoutList::iterator it =
973 remove_if(layoutlist_.begin(), layoutlist_.end(),
974 LayoutNamesEqual(name));
976 LayoutList::iterator end = layoutlist_.end();
977 bool const ret = (it != end);
978 layoutlist_.erase(it, end);
983 // Load textclass info if not loaded yet
984 bool TextClass::load(string const & path) const
989 // Read style-file, provided path is searched before the system ones
990 FileName layout_file;
992 layout_file = FileName(addName(path, name_ + ".layout"));
993 if (layout_file.empty() || !layout_file.exists())
994 layout_file = libFileSearch("layouts", name_, "layout");
995 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
998 lyxerr << "Error reading `"
999 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1000 << "'\n(Check `" << name_
1001 << "')\nCheck your installation and "
1002 "try Options/Reconfigure..." << endl;
1009 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1012 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1013 while (!n.empty()) {
1014 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1015 if (cit != cen && cit->first == n)
1017 size_t i = n.find(':');
1018 if (i == string::npos)
1022 return empty_insetlayout_;
1026 docstring const & TextClass::defaultLayoutName() const
1028 // This really should come from the actual layout... (Lgb)
1029 return defaultlayout_;
1033 Layout const & TextClass::defaultLayout() const
1035 return operator[](defaultLayoutName());
1039 bool TextClass::isDefaultLayout(Layout const & layout) const
1041 return layout.name() == defaultLayoutName();
1045 bool TextClass::isPlainLayout(Layout const & layout) const
1047 return layout.name() == emptyLayoutName();
1051 /////////////////////////////////////////////////////////////////////////
1053 // DocumentClassBundle
1055 /////////////////////////////////////////////////////////////////////////
1057 DocumentClassBundle::~DocumentClassBundle()
1059 for (size_t i = 0; i != documentClasses_.size(); ++i)
1060 delete documentClasses_[i];
1061 documentClasses_.clear();
1064 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1066 DocumentClass * dc = new DocumentClass(baseClass);
1067 documentClasses_.push_back(dc);
1068 return *documentClasses_.back();
1072 DocumentClassBundle & DocumentClassBundle::get()
1074 static DocumentClassBundle singleton;
1079 /////////////////////////////////////////////////////////////////////////
1083 /////////////////////////////////////////////////////////////////////////
1085 DocumentClass::DocumentClass(LayoutFile const & tc)
1090 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1092 LayoutList::const_iterator it = layoutlist_.begin();
1093 LayoutList::const_iterator end = layoutlist_.end();
1094 for (; it != end; ++it)
1095 if (it->latexname() == lay)
1101 bool DocumentClass::provides(string const & p) const
1103 return provides_.find(p) != provides_.end();
1107 bool DocumentClass::hasTocLevels() const
1109 return min_toclevel_ != Layout::NOT_IN_TOC;
1113 /////////////////////////////////////////////////////////////////////////
1117 /////////////////////////////////////////////////////////////////////////
1119 ostream & operator<<(ostream & os, PageSides p)