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"
40 #include "boost/assert.hpp"
43 using namespace lyx::support;
49 class LayoutNamesEqual : public unary_function<Layout, bool> {
51 LayoutNamesEqual(docstring const & name)
54 bool operator()(Layout const & c) const
56 return c.name() == name_;
66 bool layout2layout(FileName const & filename, FileName const & tempfile)
68 FileName const script = libFileSearch("scripts", "layout2layout.py");
70 lyxerr << "Could not find layout conversion "
71 "script layout2layout.py." << endl;
75 ostringstream command;
76 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
77 << ' ' << quoteName(filename.toFilesystemEncoding())
78 << ' ' << quoteName(tempfile.toFilesystemEncoding());
79 string const command_str = command.str();
81 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
84 runCommand(command_str);
86 lyxerr << "Could not run layout conversion "
87 "script layout2layout.py." << endl;
94 std::string translateRT(TextClass::ReadType rt)
97 case TextClass::BASECLASS:
99 case TextClass::MERGE:
101 case TextClass::MODULE:
102 return "module file";
111 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
114 InsetLayout DocumentClass::empty_insetlayout_;
117 TextClass::TextClass()
124 pagestyle_ = "default";
125 defaultfont_ = sane_font;
126 opt_fontsize_ = "10|11|12";
127 opt_pagestyle_ = "empty|plain|headings|fancy";
128 titletype_ = TITLE_COMMAND_AFTER;
129 titlename_ = "maketitle";
131 // a hack to make this available for translation
132 // i'm sure there must be a better way (rgh)
137 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
139 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
140 if (!lay.read(lexrc, *this)) {
141 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
145 lay.resfont = lay.font;
146 lay.resfont.realize(defaultfont_);
147 lay.reslabelfont = lay.labelfont;
148 lay.reslabelfont.realize(defaultfont_);
149 return true; // no errors
182 // Reads a textclass structure from file.
183 bool TextClass::read(FileName const & filename, ReadType rt)
185 if (!filename.isReadableFile()) {
186 lyxerr << "Cannot read layout file `" << filename << "'."
191 keyword_item textClassTags[] = {
192 { "classoptions", TC_CLASSOPTIONS },
193 { "columns", TC_COLUMNS },
194 { "counter", TC_COUNTER },
195 { "defaultfont", TC_DEFAULTFONT },
196 { "defaultstyle", TC_DEFAULTSTYLE },
197 { "environment", TC_ENVIRONMENT },
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 }
219 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
220 to_utf8(makeDisplayPath(filename.absFilename())));
222 // Define the `empty' layout used in table cells, ert, etc. Note that
223 // we do this before loading any layout file, so that classes can
224 // override features of this layout if they should choose to do so.
225 if (rt == BASECLASS) {
226 static char const * s = "Margin Static\n"
227 "LatexType Paragraph\n"
230 "AlignPossible Left, Right, Center\n"
231 "LabelType No_Label\n"
234 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
237 lay.setName(emptylayout_);
238 if (!readStyle(lex, lay)) {
239 // The only way this happens is because the hardcoded layout above
243 layoutlist_.push_back(lay);
246 Lexer lexrc(textClassTags,
247 sizeof(textClassTags) / sizeof(textClassTags[0]));
249 lexrc.setFile(filename);
250 bool error = !lexrc.isOK();
252 // Format of files before the 'Format' tag was introduced
256 while (lexrc.isOK() && !error) {
257 int le = lexrc.lex();
260 case Lexer::LEX_FEOF:
263 case Lexer::LEX_UNDEF:
264 lexrc.printError("Unknown TextClass tag `$$Token'");
272 switch (static_cast<TextClassTags>(le)) {
276 format = lexrc.getInteger();
279 case TC_OUTPUTTYPE: // output type definition
280 readOutputType(lexrc);
283 case TC_INPUT: // Include file
285 string const inc = lexrc.getString();
286 FileName tmp = libFileSearch("layouts", inc,
290 lexrc.printError("Could not find input file: " + inc);
292 } else if (!read(tmp, MERGE)) {
293 lexrc.printError("Error reading input"
294 "file: " + tmp.absFilename());
300 case TC_DEFAULTSTYLE:
302 docstring const name = from_utf8(subst(lexrc.getString(),
304 defaultlayout_ = name;
311 docstring const name = from_utf8(subst(lexrc.getString(),
314 string s = "Could not read name for style: `$$Token' "
315 + lexrc.getString() + " is probably not valid UTF-8!";
316 lexrc.printError(s.c_str());
318 //FIXME If we're just dropping this layout, do we really
319 //care whether there's an error?? Or should we just set
320 //error to true, since we couldn't even read the name?
321 error = !readStyle(lexrc, lay);
322 } else if (hasLayout(name)) {
323 Layout & lay = operator[](name);
324 error = !readStyle(lexrc, lay);
328 if (le == TC_ENVIRONMENT)
329 lay.is_environment = true;
330 error = !readStyle(lexrc, lay);
332 layoutlist_.push_back(lay);
334 if (defaultlayout_.empty()) {
335 // We do not have a default layout yet, so we choose
336 // the first layout we encounter.
337 defaultlayout_ = name;
342 //FIXME Should we also eat the style here? viz:
344 //readStyle(lexrc, lay);
346 lexrc.printError("No name given for style: `$$Token'.");
353 docstring const style = from_utf8(subst(lexrc.getString(),
355 if (!deleteLayout(style))
356 lyxerr << "Cannot delete style `"
357 << to_utf8(style) << '\'' << endl;
363 columns_ = lexrc.getInteger();
368 switch (lexrc.getInteger()) {
369 case 1: sides_ = OneSide; break;
370 case 2: sides_ = TwoSides; break;
372 lyxerr << "Impossible number of page"
373 " sides, setting to one."
383 pagestyle_ = rtrim(lexrc.getString());
387 defaultfont_ = lyxRead(lexrc);
388 if (!defaultfont_.resolved()) {
389 lexrc.printError("Warning: defaultfont should "
390 "be fully instantiated!");
391 defaultfont_.realize(sane_font);
397 secnumdepth_ = lexrc.getInteger();
402 tocdepth_ = lexrc.getInteger();
405 // First step to support options
406 case TC_CLASSOPTIONS:
407 readClassOptions(lexrc);
411 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
416 string const feature = lexrc.getString();
418 if (lexrc.getInteger())
419 provides_.insert(feature);
421 provides_.erase(feature);
427 vector<string> const req
428 = getVectorFromString(lexrc.getString());
429 requires_.insert(req.begin(), req.end());
433 case TC_LEFTMARGIN: // left margin type
435 leftmargin_ = lexrc.getDocString();
438 case TC_RIGHTMARGIN: // right margin type
440 rightmargin_ = lexrc.getDocString();
446 if (il.read(lexrc)) {
447 insetlayoutlist_[il.name()] = il;
449 // else there was an error, so forget it
461 case TC_TITLELATEXTYPE:
462 readTitleType(lexrc);
465 case TC_TITLELATEXNAME:
467 titlename_ = lexrc.getString();
472 string const nofloat = lexrc.getString();
473 floatlist_.erase(nofloat);
478 //Note that this is triggered the first time through the loop unless
479 //we hit a format tag.
480 if (format != FORMAT)
484 if (format != FORMAT) {
485 LYXERR(Debug::TCLASS, "Converting layout file from format "
486 << format << " to " << FORMAT);
487 FileName const tempfile = FileName::tempName();
488 bool success = layout2layout(filename, tempfile);
491 tempfile.removeFile();
495 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
496 to_utf8(makeDisplayPath(filename.absFilename())));
501 if (defaultlayout_.empty()) {
502 lyxerr << "Error: Textclass '" << name_
503 << "' is missing a defaultstyle." << endl;
507 //Try to erase "stdinsets" from the provides_ set.
509 // Provides stdinsets 1
510 //declaration simply tells us that the standard insets have been
511 //defined. (It's found in stdinsets.inc but could also be used in
512 //user-defined files.) There isn't really any such package. So we
513 //might as well go ahead and erase it.
514 //If we do not succeed, then it was not there, which means that
515 //the textclass did not provide the definitions of the standard
516 //insets. So we need to try to load them.
517 int erased = provides_.erase("stdinsets");
519 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
522 throw ExceptionMessage(WarningException, _("Missing File"),
523 _("Could not find stdinsets.inc! This may lead to data loss!"));
525 } else if (!read(tmp, MERGE)) {
526 throw ExceptionMessage(WarningException, _("Corrupt File"),
527 _("Could not read stdinsets.inc! This may lead to data loss!"));
532 min_toclevel_ = Layout::NOT_IN_TOC;
533 max_toclevel_ = Layout::NOT_IN_TOC;
534 const_iterator lit = begin();
535 const_iterator len = end();
536 for (; lit != len; ++lit) {
537 int const toclevel = lit->toclevel;
538 if (toclevel != Layout::NOT_IN_TOC) {
539 if (min_toclevel_ == Layout::NOT_IN_TOC)
540 min_toclevel_ = toclevel;
542 min_toclevel_ = min(min_toclevel_, toclevel);
543 max_toclevel_ = max(max_toclevel_, toclevel);
546 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
547 << ", maximum is " << max_toclevel_);
553 void TextClass::readTitleType(Lexer & lexrc)
555 keyword_item titleTypeTags[] = {
556 { "commandafter", TITLE_COMMAND_AFTER },
557 { "environment", TITLE_ENVIRONMENT }
560 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
562 int le = lexrc.lex();
564 case Lexer::LEX_UNDEF:
565 lexrc.printError("Unknown output type `$$Token'");
567 case TITLE_COMMAND_AFTER:
568 case TITLE_ENVIRONMENT:
569 titletype_ = static_cast<TitleLatexType>(le);
572 lyxerr << "Unhandled value " << le
573 << " in TextClass::readTitleType." << endl;
580 void TextClass::readOutputType(Lexer & lexrc)
582 keyword_item outputTypeTags[] = {
583 { "docbook", DOCBOOK },
585 { "literate", LITERATE }
588 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
590 int le = lexrc.lex();
592 case Lexer::LEX_UNDEF:
593 lexrc.printError("Unknown output type `$$Token'");
598 outputType_ = static_cast<OutputType>(le);
601 lyxerr << "Unhandled value " << le
602 << " in TextClass::readOutputType." << endl;
609 enum ClassOptionsTags {
618 void TextClass::readClassOptions(Lexer & lexrc)
620 keyword_item classOptionsTags[] = {
622 {"fontsize", CO_FONTSIZE },
623 {"header", CO_HEADER },
624 {"other", CO_OTHER },
625 {"pagestyle", CO_PAGESTYLE }
628 lexrc.pushTable(classOptionsTags, CO_END);
630 while (!getout && lexrc.isOK()) {
631 int le = lexrc.lex();
633 case Lexer::LEX_UNDEF:
634 lexrc.printError("Unknown ClassOption tag `$$Token'");
638 switch (static_cast<ClassOptionsTags>(le)) {
641 opt_fontsize_ = rtrim(lexrc.getString());
645 opt_pagestyle_ = rtrim(lexrc.getString());
649 options_ = lexrc.getString();
653 class_header_ = subst(lexrc.getString(), """, "\"");
677 void TextClass::readFloat(Lexer & lexrc)
679 keyword_item floatTags[] = {
681 { "extension", FT_EXT },
682 { "guiname", FT_NAME },
683 { "latexbuiltin", FT_BUILTIN },
684 { "listname", FT_LISTNAME },
685 { "numberwithin", FT_WITHIN },
686 { "placement", FT_PLACEMENT },
687 { "style", FT_STYLE },
691 lexrc.pushTable(floatTags, FT_END);
700 bool builtin = false;
703 while (!getout && lexrc.isOK()) {
704 int le = lexrc.lex();
706 case Lexer::LEX_UNDEF:
707 lexrc.printError("Unknown float tag `$$Token'");
711 switch (static_cast<FloatTags>(le)) {
714 type = lexrc.getString();
715 if (floatlist_.typeExist(type)) {
716 Floating const & fl = floatlist_.getType(type);
717 placement = fl.placement();
719 within = fl.within();
722 listName = fl.listName();
723 builtin = fl.builtin();
728 name = lexrc.getString();
732 placement = lexrc.getString();
736 ext = lexrc.getString();
740 within = lexrc.getString();
741 if (within == "none")
746 style = lexrc.getString();
750 listName = lexrc.getString();
754 builtin = lexrc.getBool();
762 // Here if have a full float if getout == true
764 Floating fl(type, placement, ext, within,
765 style, name, listName, builtin);
766 floatlist_.newFloat(fl);
767 // each float has its own counter
768 counters_.newCounter(from_ascii(type), from_ascii(within),
769 docstring(), docstring());
770 // also define sub-float counters
771 docstring const subtype = "sub-" + from_ascii(type);
772 counters_.newCounter(subtype, from_ascii(type),
773 "\\alph{" + subtype + "}", docstring());
784 CT_LABELSTRING_APPENDIX,
789 void TextClass::readCounter(Lexer & lexrc)
791 keyword_item counterTags[] = {
793 { "labelstring", CT_LABELSTRING },
794 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
796 { "within", CT_WITHIN }
799 lexrc.pushTable(counterTags, CT_END);
803 docstring labelstring;
804 docstring labelstring_appendix;
807 while (!getout && lexrc.isOK()) {
808 int le = lexrc.lex();
810 case Lexer::LEX_UNDEF:
811 lexrc.printError("Unknown counter tag `$$Token'");
815 switch (static_cast<CounterTags>(le)) {
818 name = lexrc.getDocString();
819 if (counters_.hasCounter(name))
820 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
822 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
826 within = lexrc.getDocString();
827 if (within == "none")
832 labelstring = lexrc.getDocString();
833 labelstring_appendix = labelstring;
835 case CT_LABELSTRING_APPENDIX:
837 labelstring_appendix = lexrc.getDocString();
845 // Here if have a full counter if getout == true
847 counters_.newCounter(name, within,
848 labelstring, labelstring_appendix);
854 bool TextClass::hasLayout(docstring const & n) const
856 docstring const name = n.empty() ? defaultLayoutName() : n;
858 return find_if(layoutlist_.begin(), layoutlist_.end(),
859 LayoutNamesEqual(name))
860 != layoutlist_.end();
865 Layout const & TextClass::operator[](docstring const & name) const
867 BOOST_ASSERT(!name.empty());
870 find_if(begin(), end(), LayoutNamesEqual(name));
873 lyxerr << "We failed to find the layout '" << to_utf8(name)
874 << "' in the layout list. You MUST investigate!"
876 for (const_iterator cit = begin(); cit != end(); ++cit)
877 lyxerr << " " << to_utf8(cit->name()) << endl;
879 // we require the name to exist
887 Layout & TextClass::operator[](docstring const & name)
889 BOOST_ASSERT(!name.empty());
891 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
894 lyxerr << "We failed to find the layout '" << to_utf8(name)
895 << "' in the layout list. You MUST investigate!"
897 for (const_iterator cit = begin(); cit != end(); ++cit)
898 lyxerr << " " << to_utf8(cit->name()) << endl;
900 // we require the name to exist
908 bool TextClass::deleteLayout(docstring const & name)
910 if (name == defaultLayoutName() || name == emptyLayoutName())
913 LayoutList::iterator it =
914 remove_if(layoutlist_.begin(), layoutlist_.end(),
915 LayoutNamesEqual(name));
917 LayoutList::iterator end = layoutlist_.end();
918 bool const ret = (it != end);
919 layoutlist_.erase(it, end);
924 // Load textclass info if not loaded yet
925 bool TextClass::load(string const & path) const
930 // Read style-file, provided path is searched before the system ones
931 FileName layout_file;
933 layout_file = FileName(addName(path, name_ + ".layout"));
934 if (layout_file.empty() || !layout_file.exists())
935 layout_file = libFileSearch("layouts", name_, "layout");
936 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
939 lyxerr << "Error reading `"
940 << to_utf8(makeDisplayPath(layout_file.absFilename()))
941 << "'\n(Check `" << name_
942 << "')\nCheck your installation and "
943 "try Options/Reconfigure..." << endl;
950 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
953 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
955 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
956 if (cit != cen && cit->first == n)
958 size_t i = n.find(':');
959 if (i == string::npos)
963 return empty_insetlayout_;
967 docstring const & TextClass::defaultLayoutName() const
969 // This really should come from the actual layout... (Lgb)
970 return defaultlayout_;
974 Layout const & TextClass::defaultLayout() const
976 return operator[](defaultLayoutName());
980 bool TextClass::isDefaultLayout(Layout const & lay) const
982 return lay.name() == defaultLayoutName();
986 bool TextClass::isEmptyLayout(Layout const & lay) const
988 return lay.name() == emptyLayoutName();
992 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
994 DocumentClass * dc = new DocumentClass(baseClass);
995 tc_list_.push_back(dc);
996 return *tc_list_.back();
1000 DocumentClassBundle & DocumentClassBundle::get()
1002 static DocumentClassBundle singleton;
1007 DocumentClass::DocumentClass(LayoutFile const & tc)
1012 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1014 LayoutList::const_iterator it = layoutlist_.begin();
1015 LayoutList::const_iterator end = layoutlist_.end();
1016 for (; it != end; ++it)
1017 if (it->latexname() == lay)
1023 bool DocumentClass::provides(string const & p) const
1025 return provides_.find(p) != provides_.end();
1029 bool DocumentClass::hasTocLevels() const
1031 return min_toclevel_ != Layout::NOT_IN_TOC;
1035 ostream & operator<<(ostream & os, PageSides p)