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/assert.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 TextClass::TextClass()
127 pagestyle_ = "default";
128 defaultfont_ = sane_font;
129 opt_fontsize_ = "10|11|12";
130 opt_pagestyle_ = "empty|plain|headings|fancy";
131 titletype_ = TITLE_COMMAND_AFTER;
132 titlename_ = "maketitle";
134 _("Plain Layout"); // a hack to make this translatable
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 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
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
259 LASSERT(false, /**/);
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 LYXERR0("Unable to create tempoary file");
311 // now try to convert it
312 bool const worx = convertLayoutFormat(tempfile, rt);
314 LYXERR0("Unable to convert internal layout information to format "
317 tempfile.removeFile();
322 // Reads a textclass structure from file.
323 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
325 bool error = !lexrc.isOK();
327 // Format of files before the 'Format' tag was introduced
331 while (lexrc.isOK() && !error) {
332 int le = lexrc.lex();
335 case Lexer::LEX_FEOF:
338 case Lexer::LEX_UNDEF:
339 lexrc.printError("Unknown TextClass tag `$$Token'");
347 switch (static_cast<TextClassTags>(le)) {
351 format = lexrc.getInteger();
354 case TC_OUTPUTTYPE: // output type definition
355 readOutputType(lexrc);
358 case TC_INPUT: // Include file
360 string const inc = lexrc.getString();
361 FileName tmp = libFileSearch("layouts", inc,
365 lexrc.printError("Could not find input file: " + inc);
367 } else if (!read(tmp, MERGE)) {
368 lexrc.printError("Error reading input"
369 "file: " + tmp.absFilename());
375 case TC_DEFAULTSTYLE:
377 docstring const name = from_utf8(subst(lexrc.getString(),
379 defaultlayout_ = name;
386 docstring const name = from_utf8(subst(lexrc.getString(),
389 string s = "Could not read name for style: `$$Token' "
390 + lexrc.getString() + " is probably not valid UTF-8!";
391 lexrc.printError(s.c_str());
393 // Since we couldn't read the name, we just scan the rest
394 // of the style and discard it.
395 error = !readStyle(lexrc, lay);
396 } else if (hasLayout(name)) {
397 Layout & lay = operator[](name);
398 error = !readStyle(lexrc, lay);
401 layout.setName(name);
402 if (le == TC_ENVIRONMENT)
403 layout.is_environment = true;
404 error = !readStyle(lexrc, layout);
406 layoutlist_.push_back(layout);
408 if (defaultlayout_.empty()) {
409 // We do not have a default layout yet, so we choose
410 // the first layout we encounter.
411 defaultlayout_ = name;
416 //FIXME Should we also eat the style here? viz:
418 //readStyle(lexrc, layout);
420 lexrc.printError("No name given for style: `$$Token'.");
427 docstring const style = from_utf8(subst(lexrc.getString(),
429 if (!deleteLayout(style))
430 lyxerr << "Cannot delete style `"
431 << to_utf8(style) << '\'' << endl;
437 columns_ = lexrc.getInteger();
442 switch (lexrc.getInteger()) {
443 case 1: sides_ = OneSide; break;
444 case 2: sides_ = TwoSides; break;
446 lyxerr << "Impossible number of page"
447 " sides, setting to one."
457 pagestyle_ = rtrim(lexrc.getString());
461 defaultfont_ = lyxRead(lexrc);
462 if (!defaultfont_.resolved()) {
463 lexrc.printError("Warning: defaultfont should "
464 "be fully instantiated!");
465 defaultfont_.realize(sane_font);
471 secnumdepth_ = lexrc.getInteger();
476 tocdepth_ = lexrc.getInteger();
479 // First step to support options
480 case TC_CLASSOPTIONS:
481 readClassOptions(lexrc);
485 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
488 case TC_ADDTOPREAMBLE:
489 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
494 string const feature = lexrc.getString();
496 if (lexrc.getInteger())
497 provides_.insert(feature);
499 provides_.erase(feature);
505 vector<string> const req
506 = getVectorFromString(lexrc.getString());
507 requires_.insert(req.begin(), req.end());
511 case TC_LEFTMARGIN: // left margin type
513 leftmargin_ = lexrc.getDocString();
516 case TC_RIGHTMARGIN: // right margin type
518 rightmargin_ = lexrc.getDocString();
525 insetlayoutlist_[il.name()] = il;
526 // else there was an error, so forget it
538 case TC_TITLELATEXTYPE:
539 readTitleType(lexrc);
542 case TC_TITLELATEXNAME:
544 titlename_ = lexrc.getString();
549 string const nofloat = lexrc.getString();
550 floatlist_.erase(nofloat);
555 //Note that this is triggered the first time through the loop unless
556 //we hit a format tag.
557 if (format != FORMAT)
561 if (format != FORMAT)
562 return FORMAT_MISMATCH;
565 return (error ? ERROR : OK);
567 if (defaultlayout_.empty()) {
568 LYXERR0("Error: Textclass '" << name_
569 << "' is missing a defaultstyle.");
573 // Try to erase "stdinsets" from the provides_ set.
575 // Provides stdinsets 1
576 // declaration simply tells us that the standard insets have been
577 // defined. (It's found in stdinsets.inc but could also be used in
578 // user-defined files.) There isn't really any such package. So we
579 // might as well go ahead and erase it.
580 // If we do not succeed, then it was not there, which means that
581 // the textclass did not provide the definitions of the standard
582 // insets. So we need to try to load them.
583 int erased = provides_.erase("stdinsets");
585 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
588 throw ExceptionMessage(WarningException, _("Missing File"),
589 _("Could not find stdinsets.inc! This may lead to data loss!"));
591 } else if (!read(tmp, MERGE)) {
592 throw ExceptionMessage(WarningException, _("Corrupt File"),
593 _("Could not read stdinsets.inc! This may lead to data loss!"));
598 min_toclevel_ = Layout::NOT_IN_TOC;
599 max_toclevel_ = Layout::NOT_IN_TOC;
600 const_iterator lit = begin();
601 const_iterator len = end();
602 for (; lit != len; ++lit) {
603 int const toclevel = lit->toclevel;
604 if (toclevel != Layout::NOT_IN_TOC) {
605 if (min_toclevel_ == Layout::NOT_IN_TOC)
606 min_toclevel_ = toclevel;
608 min_toclevel_ = min(min_toclevel_, toclevel);
609 max_toclevel_ = max(max_toclevel_, toclevel);
612 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
613 << ", maximum is " << max_toclevel_);
615 return (error ? ERROR : OK);
619 void TextClass::readTitleType(Lexer & lexrc)
621 LexerKeyword titleTypeTags[] = {
622 { "commandafter", TITLE_COMMAND_AFTER },
623 { "environment", TITLE_ENVIRONMENT }
626 PushPopHelper pph(lexrc, titleTypeTags);
628 int le = lexrc.lex();
630 case Lexer::LEX_UNDEF:
631 lexrc.printError("Unknown output type `$$Token'");
633 case TITLE_COMMAND_AFTER:
634 case TITLE_ENVIRONMENT:
635 titletype_ = static_cast<TitleLatexType>(le);
638 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
644 void TextClass::readOutputType(Lexer & lexrc)
646 LexerKeyword outputTypeTags[] = {
647 { "docbook", DOCBOOK },
649 { "literate", LITERATE }
652 PushPopHelper pph(lexrc, outputTypeTags);
654 int le = lexrc.lex();
656 case Lexer::LEX_UNDEF:
657 lexrc.printError("Unknown output type `$$Token'");
662 outputType_ = static_cast<OutputType>(le);
665 LYXERR0("Unhandled value " << le);
671 void TextClass::readClassOptions(Lexer & lexrc)
681 LexerKeyword classOptionsTags[] = {
683 {"fontsize", CO_FONTSIZE },
684 {"header", CO_HEADER },
685 {"other", CO_OTHER },
686 {"pagestyle", CO_PAGESTYLE }
689 lexrc.pushTable(classOptionsTags);
691 while (!getout && lexrc.isOK()) {
692 int le = lexrc.lex();
694 case Lexer::LEX_UNDEF:
695 lexrc.printError("Unknown ClassOption tag `$$Token'");
702 opt_fontsize_ = rtrim(lexrc.getString());
706 opt_pagestyle_ = rtrim(lexrc.getString());
710 options_ = lexrc.getString();
714 class_header_ = subst(lexrc.getString(), """, "\"");
725 void TextClass::readFloat(Lexer & lexrc)
739 LexerKeyword floatTags[] = {
741 { "extension", FT_EXT },
742 { "guiname", FT_NAME },
743 { "latexbuiltin", FT_BUILTIN },
744 { "listname", FT_LISTNAME },
745 { "numberwithin", FT_WITHIN },
746 { "placement", FT_PLACEMENT },
747 { "style", FT_STYLE },
751 lexrc.pushTable(floatTags);
760 bool builtin = false;
763 while (!getout && lexrc.isOK()) {
764 int le = lexrc.lex();
766 case Lexer::LEX_UNDEF:
767 lexrc.printError("Unknown float tag `$$Token'");
774 type = lexrc.getString();
775 if (floatlist_.typeExist(type)) {
776 Floating const & fl = floatlist_.getType(type);
777 placement = fl.placement();
779 within = fl.within();
782 listName = fl.listName();
783 builtin = fl.builtin();
788 name = lexrc.getString();
792 placement = lexrc.getString();
796 ext = lexrc.getString();
800 within = lexrc.getString();
801 if (within == "none")
806 style = lexrc.getString();
810 listName = lexrc.getString();
814 builtin = lexrc.getBool();
822 // Here if have a full float if getout == true
824 Floating fl(type, placement, ext, within,
825 style, name, listName, builtin);
826 floatlist_.newFloat(fl);
827 // each float has its own counter
828 counters_.newCounter(from_ascii(type), from_ascii(within),
829 docstring(), docstring());
830 // also define sub-float counters
831 docstring const subtype = "sub-" + from_ascii(type);
832 counters_.newCounter(subtype, from_ascii(type),
833 "\\alph{" + subtype + "}", docstring());
840 void TextClass::readCounter(Lexer & lexrc)
846 CT_LABELSTRING_APPENDIX,
850 LexerKeyword counterTags[] = {
852 { "labelstring", CT_LABELSTRING },
853 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
855 { "within", CT_WITHIN }
858 lexrc.pushTable(counterTags);
862 docstring labelstring;
863 docstring labelstring_appendix;
866 while (!getout && lexrc.isOK()) {
867 int le = lexrc.lex();
869 case Lexer::LEX_UNDEF:
870 lexrc.printError("Unknown counter tag `$$Token'");
877 name = lexrc.getDocString();
878 if (counters_.hasCounter(name))
879 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
881 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
885 within = lexrc.getDocString();
886 if (within == "none")
891 labelstring = lexrc.getDocString();
892 labelstring_appendix = labelstring;
894 case CT_LABELSTRING_APPENDIX:
896 labelstring_appendix = lexrc.getDocString();
904 // Here if have a full counter if getout == true
906 counters_.newCounter(name, within,
907 labelstring, labelstring_appendix);
913 bool TextClass::hasLayout(docstring const & n) const
915 docstring const name = n.empty() ? defaultLayoutName() : n;
917 return find_if(layoutlist_.begin(), layoutlist_.end(),
918 LayoutNamesEqual(name))
919 != layoutlist_.end();
924 Layout const & TextClass::operator[](docstring const & name) const
926 LASSERT(!name.empty(), /**/);
929 find_if(begin(), end(), LayoutNamesEqual(name));
932 lyxerr << "We failed to find the layout '" << to_utf8(name)
933 << "' in the layout list. You MUST investigate!"
935 for (const_iterator cit = begin(); cit != end(); ++cit)
936 lyxerr << " " << to_utf8(cit->name()) << endl;
938 // we require the name to exist
939 LASSERT(false, /**/);
946 Layout & TextClass::operator[](docstring const & name)
948 LASSERT(!name.empty(), /**/);
950 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
953 LYXERR0("We failed to find the layout '" << to_utf8(name)
954 << "' in the layout list. You MUST investigate!");
955 for (const_iterator cit = begin(); cit != end(); ++cit)
956 LYXERR0(" " << to_utf8(cit->name()));
958 // we require the name to exist
959 LASSERT(false, /**/);
966 bool TextClass::deleteLayout(docstring const & name)
968 if (name == defaultLayoutName() || name == emptyLayoutName())
971 LayoutList::iterator it =
972 remove_if(layoutlist_.begin(), layoutlist_.end(),
973 LayoutNamesEqual(name));
975 LayoutList::iterator end = layoutlist_.end();
976 bool const ret = (it != end);
977 layoutlist_.erase(it, end);
982 // Load textclass info if not loaded yet
983 bool TextClass::load(string const & path) const
988 // Read style-file, provided path is searched before the system ones
989 FileName layout_file;
991 layout_file = FileName(addName(path, name_ + ".layout"));
992 if (layout_file.empty() || !layout_file.exists())
993 layout_file = libFileSearch("layouts", name_, "layout");
994 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
997 lyxerr << "Error reading `"
998 << to_utf8(makeDisplayPath(layout_file.absFilename()))
999 << "'\n(Check `" << name_
1000 << "')\nCheck your installation and "
1001 "try Options/Reconfigure..." << endl;
1008 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1011 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1012 while (!n.empty()) {
1013 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1014 if (cit != cen && cit->first == n)
1016 size_t i = n.find(':');
1017 if (i == string::npos)
1021 return empty_insetlayout_;
1025 docstring const & TextClass::defaultLayoutName() const
1027 // This really should come from the actual layout... (Lgb)
1028 return defaultlayout_;
1032 Layout const & TextClass::defaultLayout() const
1034 return operator[](defaultLayoutName());
1038 bool TextClass::isDefaultLayout(Layout const & lay) const
1040 return lay.name() == defaultLayoutName();
1044 bool TextClass::isEmptyLayout(Layout const & lay) const
1046 return lay.name() == emptyLayoutName();
1050 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1052 DocumentClass * dc = new DocumentClass(baseClass);
1053 tc_list_.push_back(dc);
1054 return *tc_list_.back();
1058 DocumentClassBundle & DocumentClassBundle::get()
1060 static DocumentClassBundle singleton;
1065 DocumentClass::DocumentClass(LayoutFile const & tc)
1070 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1072 LayoutList::const_iterator it = layoutlist_.begin();
1073 LayoutList::const_iterator end = layoutlist_.end();
1074 for (; it != end; ++it)
1075 if (it->latexname() == lay)
1081 bool DocumentClass::provides(string const & p) const
1083 return provides_.find(p) != provides_.end();
1087 bool DocumentClass::hasTocLevels() const
1089 return min_toclevel_ != Layout::NOT_IN_TOC;
1093 ostream & operator<<(ostream & os, PageSides p)