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 "BaseClassList.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"
41 using namespace lyx::support;
47 class LayoutNamesEqual : public unary_function<LayoutPtr, bool> {
49 LayoutNamesEqual(docstring const & name)
52 bool operator()(LayoutPtr const & c) const
54 return c->name() == name_;
64 bool layout2layout(FileName const & filename, FileName const & tempfile)
66 FileName const script = libFileSearch("scripts", "layout2layout.py");
68 lyxerr << "Could not find layout conversion "
69 "script layout2layout.py." << endl;
73 ostringstream command;
74 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
75 << ' ' << quoteName(filename.toFilesystemEncoding())
76 << ' ' << quoteName(tempfile.toFilesystemEncoding());
77 string const command_str = command.str();
79 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
82 runCommand(command_str);
84 lyxerr << "Could not run layout conversion "
85 "script layout2layout.py." << endl;
92 std::string translateRT(TextClass::ReadType rt)
95 case TextClass::BASECLASS:
97 case TextClass::MERGE:
99 case TextClass::MODULE:
100 return "module file";
109 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
112 InsetLayout DocumentClass::empty_insetlayout_;
115 TextClass::TextClass()
117 floatlist_ = boost::shared_ptr<FloatList>(new FloatList);
118 counters_ = boost::shared_ptr<Counters>(new Counters);
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(boost::shared_ptr<Layout>(new Layout(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).get();
324 error = !readStyle(lexrc, *lay);
328 if (le == TC_ENVIRONMENT)
329 lay.is_environment = true;
330 error = !readStyle(lexrc, lay);
332 layoutlist_.push_back(boost::shared_ptr<Layout>(new Layout(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 for (size_t i = 0; i != layoutCount(); ++i) {
535 int const toclevel = layout(i)->toclevel;
536 if (toclevel != Layout::NOT_IN_TOC) {
537 if (min_toclevel_ == Layout::NOT_IN_TOC)
538 min_toclevel_ = toclevel;
540 min_toclevel_ = min(min_toclevel_, toclevel);
541 max_toclevel_ = max(max_toclevel_, toclevel);
544 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
545 << ", maximum is " << max_toclevel_);
551 void TextClass::readTitleType(Lexer & lexrc)
553 keyword_item titleTypeTags[] = {
554 { "commandafter", TITLE_COMMAND_AFTER },
555 { "environment", TITLE_ENVIRONMENT }
558 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
560 int le = lexrc.lex();
562 case Lexer::LEX_UNDEF:
563 lexrc.printError("Unknown output type `$$Token'");
565 case TITLE_COMMAND_AFTER:
566 case TITLE_ENVIRONMENT:
567 titletype_ = static_cast<TitleLatexType>(le);
570 lyxerr << "Unhandled value " << le
571 << " in TextClass::readTitleType." << endl;
578 void TextClass::readOutputType(Lexer & lexrc)
580 keyword_item outputTypeTags[] = {
581 { "docbook", DOCBOOK },
583 { "literate", LITERATE }
586 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
588 int le = lexrc.lex();
590 case Lexer::LEX_UNDEF:
591 lexrc.printError("Unknown output type `$$Token'");
596 outputType_ = static_cast<OutputType>(le);
599 lyxerr << "Unhandled value " << le
600 << " in TextClass::readOutputType." << endl;
607 enum ClassOptionsTags {
616 void TextClass::readClassOptions(Lexer & lexrc)
618 keyword_item classOptionsTags[] = {
620 {"fontsize", CO_FONTSIZE },
621 {"header", CO_HEADER },
622 {"other", CO_OTHER },
623 {"pagestyle", CO_PAGESTYLE }
626 lexrc.pushTable(classOptionsTags, CO_END);
628 while (!getout && lexrc.isOK()) {
629 int le = lexrc.lex();
631 case Lexer::LEX_UNDEF:
632 lexrc.printError("Unknown ClassOption tag `$$Token'");
636 switch (static_cast<ClassOptionsTags>(le)) {
639 opt_fontsize_ = rtrim(lexrc.getString());
643 opt_pagestyle_ = rtrim(lexrc.getString());
647 options_ = lexrc.getString();
651 class_header_ = subst(lexrc.getString(), """, "\"");
675 void TextClass::readFloat(Lexer & lexrc)
677 keyword_item floatTags[] = {
679 { "extension", FT_EXT },
680 { "guiname", FT_NAME },
681 { "latexbuiltin", FT_BUILTIN },
682 { "listname", FT_LISTNAME },
683 { "numberwithin", FT_WITHIN },
684 { "placement", FT_PLACEMENT },
685 { "style", FT_STYLE },
689 lexrc.pushTable(floatTags, FT_END);
698 bool builtin = false;
701 while (!getout && lexrc.isOK()) {
702 int le = lexrc.lex();
704 case Lexer::LEX_UNDEF:
705 lexrc.printError("Unknown float tag `$$Token'");
709 switch (static_cast<FloatTags>(le)) {
712 type = lexrc.getString();
713 if (floatlist_->typeExist(type)) {
714 Floating const & fl = floatlist_->getType(type);
715 placement = fl.placement();
717 within = fl.within();
720 listName = fl.listName();
721 builtin = fl.builtin();
726 name = lexrc.getString();
730 placement = lexrc.getString();
734 ext = lexrc.getString();
738 within = lexrc.getString();
739 if (within == "none")
744 style = lexrc.getString();
748 listName = lexrc.getString();
752 builtin = lexrc.getBool();
760 // Here if have a full float if getout == true
762 Floating fl(type, placement, ext, within,
763 style, name, listName, builtin);
764 floatlist_->newFloat(fl);
765 // each float has its own counter
766 counters_->newCounter(from_ascii(type), from_ascii(within),
767 docstring(), docstring());
768 // also define sub-float counters
769 docstring const subtype = "sub-" + from_ascii(type);
770 counters_->newCounter(subtype, from_ascii(type),
771 "\\alph{" + subtype + "}", docstring());
782 CT_LABELSTRING_APPENDIX,
787 void TextClass::readCounter(Lexer & lexrc)
789 keyword_item counterTags[] = {
791 { "labelstring", CT_LABELSTRING },
792 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
794 { "within", CT_WITHIN }
797 lexrc.pushTable(counterTags, CT_END);
801 docstring labelstring;
802 docstring labelstring_appendix;
805 while (!getout && lexrc.isOK()) {
806 int le = lexrc.lex();
808 case Lexer::LEX_UNDEF:
809 lexrc.printError("Unknown counter tag `$$Token'");
813 switch (static_cast<CounterTags>(le)) {
816 name = lexrc.getDocString();
817 if (counters_->hasCounter(name))
818 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
820 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
824 within = lexrc.getDocString();
825 if (within == "none")
830 labelstring = lexrc.getDocString();
831 labelstring_appendix = labelstring;
833 case CT_LABELSTRING_APPENDIX:
835 labelstring_appendix = lexrc.getDocString();
843 // Here if have a full counter if getout == true
845 counters_->newCounter(name, within,
846 labelstring, labelstring_appendix);
852 bool TextClass::hasLayout(docstring const & n) const
854 docstring const name = n.empty() ? defaultLayoutName() : n;
856 return find_if(layoutlist_.begin(), layoutlist_.end(),
857 LayoutNamesEqual(name))
858 != layoutlist_.end();
863 LayoutPtr const & TextClass::operator[](docstring const & name) const
865 BOOST_ASSERT(!name.empty());
867 LayoutList::const_iterator cit =
868 find_if(layoutlist_.begin(),
870 LayoutNamesEqual(name));
872 if (cit == layoutlist_.end()) {
873 lyxerr << "We failed to find the layout '" << to_utf8(name)
874 << "' in the layout list. You MUST investigate!"
876 for (LayoutList::const_iterator it = layoutlist_.begin();
877 it != layoutlist_.end(); ++it)
878 lyxerr << " " << to_utf8(it->get()->name()) << endl;
880 // we require the name to exist
888 bool TextClass::deleteLayout(docstring const & name)
890 if (name == defaultLayoutName() || name == emptyLayoutName())
893 LayoutList::iterator it =
894 remove_if(layoutlist_.begin(), layoutlist_.end(),
895 LayoutNamesEqual(name));
897 LayoutList::iterator end = layoutlist_.end();
898 bool const ret = (it != end);
899 layoutlist_.erase(it, end);
904 // Load textclass info if not loaded yet
905 bool TextClass::load(string const & path) const
910 // Read style-file, provided path is searched before the system ones
911 FileName layout_file;
913 layout_file = FileName(addName(path, name_ + ".layout"));
914 if (layout_file.empty() || !layout_file.exists())
915 layout_file = libFileSearch("layouts", name_, "layout");
916 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
919 lyxerr << "Error reading `"
920 << to_utf8(makeDisplayPath(layout_file.absFilename()))
921 << "'\n(Check `" << name_
922 << "')\nCheck your installation and "
923 "try Options/Reconfigure..." << endl;
930 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
934 if (insetlayoutlist_.count(n) > 0)
935 return insetlayoutlist_[n];
936 size_t i = n.find(':');
937 if (i == string::npos)
941 return empty_insetlayout_;
945 docstring const & TextClass::defaultLayoutName() const
947 // This really should come from the actual layout... (Lgb)
948 return defaultlayout_;
952 LayoutPtr const & TextClass::defaultLayout() const
954 return operator[](defaultLayoutName());
958 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
960 DocumentClass dc(baseClass);
961 tc_list_.push_back(dc);
962 return tc_list_.back();
966 DocumentClassBundle & DocumentClassBundle::get()
968 static DocumentClassBundle singleton;
973 DocumentClass::DocumentClass(LayoutFile const & tc)
978 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
980 LayoutList::const_iterator it = layoutlist_.begin();
981 LayoutList::const_iterator end = layoutlist_.end();
982 for (; it != end; ++it)
983 if (it->get()->latexname() == lay)
989 bool DocumentClass::provides(string const & p) const
991 return provides_.find(p) != provides_.end();
995 bool DocumentClass::hasTocLevels() const
997 return min_toclevel_ != Layout::NOT_IN_TOC;
1001 ostream & operator<<(ostream & os, PageSides p)