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"
21 #include "support/debug.h"
22 #include "support/gettext.h"
24 #include "FloatList.h"
29 #include "frontends/alert.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/lstrings.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/os.h"
40 using namespace lyx::support;
46 class LayoutNamesEqual : public unary_function<LayoutPtr, bool> {
48 LayoutNamesEqual(docstring const & name)
51 bool operator()(LayoutPtr const & c) const
53 return c->name() == name_;
63 bool layout2layout(FileName const & filename, FileName const & tempfile)
65 FileName const script = libFileSearch("scripts", "layout2layout.py");
67 lyxerr << "Could not find layout conversion "
68 "script layout2layout.py." << endl;
72 ostringstream command;
73 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
74 << ' ' << quoteName(filename.toFilesystemEncoding())
75 << ' ' << quoteName(tempfile.toFilesystemEncoding());
76 string const command_str = command.str();
78 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
81 runCommand(command_str);
83 lyxerr << "Could not run layout conversion "
84 "script layout2layout.py." << endl;
91 std::string translateRT(TextClass::ReadType rt)
94 case TextClass::BASECLASS:
96 case TextClass::MERGE:
98 case TextClass::MODULE:
108 TextClass::TextClass(string const & fn, string const & cln,
109 string const & desc, bool texClassAvail )
110 : name_(fn), latexname_(cln), description_(desc),
111 floatlist_(new FloatList), counters_(new Counters),
112 texClassAvail_(texClassAvail)
120 pagestyle_ = "default";
121 defaultfont_ = sane_font;
122 opt_fontsize_ = "10|11|12";
123 opt_pagestyle_ = "empty|plain|headings|fancy";
124 titletype_ = TITLE_COMMAND_AFTER;
125 titlename_ = "maketitle";
130 bool TextClass::isTeXClassAvailable() const
132 return texClassAvail_;
136 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
138 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
139 if (!lay.read(lexrc, *this)) {
141 lay.resfont = lay.font;
142 lay.resfont.realize(defaultfont());
143 lay.reslabelfont = lay.labelfont;
144 lay.reslabelfont.realize(defaultfont());
145 return false; // no errors
147 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
181 // Reads a textclass structure from file.
182 bool TextClass::read(FileName const & filename, ReadType rt)
184 if (!filename.isReadableFile()) {
185 lyxerr << "Cannot read layout file `" << filename << "'."
190 keyword_item textClassTags[] = {
191 { "classoptions", TC_CLASSOPTIONS },
192 { "columns", TC_COLUMNS },
193 { "counter", TC_COUNTER },
194 { "defaultfont", TC_DEFAULTFONT },
195 { "defaultstyle", TC_DEFAULTSTYLE },
196 { "environment", TC_ENVIRONMENT },
197 { "float", TC_FLOAT },
198 { "format", TC_FORMAT },
199 { "input", TC_INPUT },
200 { "insetlayout", TC_INSETLAYOUT },
201 { "leftmargin", TC_LEFTMARGIN },
202 { "nofloat", TC_NOFLOAT },
203 { "nostyle", TC_NOSTYLE },
204 { "outputtype", TC_OUTPUTTYPE },
205 { "pagestyle", TC_PAGESTYLE },
206 { "preamble", TC_PREAMBLE },
207 { "provides", TC_PROVIDES },
208 { "requires", TC_REQUIRES },
209 { "rightmargin", TC_RIGHTMARGIN },
210 { "secnumdepth", TC_SECNUMDEPTH },
211 { "sides", TC_SIDES },
212 { "style", TC_STYLE },
213 { "titlelatexname", TC_TITLELATEXNAME },
214 { "titlelatextype", TC_TITLELATEXTYPE },
215 { "tocdepth", TC_TOCDEPTH }
218 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
219 to_utf8(makeDisplayPath(filename.absFilename())));
221 Lexer lexrc(textClassTags,
222 sizeof(textClassTags) / sizeof(textClassTags[0]));
224 lexrc.setFile(filename);
225 bool error = !lexrc.isOK();
227 // Format of files before the 'Format' tag was introduced
231 while (lexrc.isOK() && !error) {
232 int le = lexrc.lex();
235 case Lexer::LEX_FEOF:
238 case Lexer::LEX_UNDEF:
239 lexrc.printError("Unknown TextClass tag `$$Token'");
247 switch (static_cast<TextClassTags>(le)) {
251 format = lexrc.getInteger();
254 case TC_OUTPUTTYPE: // output type definition
255 readOutputType(lexrc);
258 case TC_INPUT: // Include file
260 string const inc = lexrc.getString();
261 FileName tmp = libFileSearch("layouts", inc,
265 lexrc.printError("Could not find input file: " + inc);
267 } else if (read(tmp, MERGE)) {
268 lexrc.printError("Error reading input"
269 "file: " + tmp.absFilename());
275 case TC_DEFAULTSTYLE:
277 docstring const name = from_utf8(subst(lexrc.getString(),
279 defaultlayout_ = name;
286 docstring const name = from_utf8(subst(lexrc.getString(),
289 string s = "Could not read name for style: `$$Token' "
290 + lexrc.getString() + " is probably not valid UTF-8!";
291 lexrc.printError(s.c_str());
293 error = readStyle(lexrc, lay);
294 } else if (hasLayout(name)) {
295 Layout * lay = operator[](name).get();
296 error = readStyle(lexrc, *lay);
300 if (le == TC_ENVIRONMENT)
301 lay.is_environment = true;
302 error = readStyle(lexrc, lay);
304 layoutlist_.push_back(
305 boost::shared_ptr<Layout>(new Layout(lay))
308 if (defaultlayout_.empty()) {
309 // We do not have a default
310 // layout yet, so we choose
311 // the first layout we
313 defaultlayout_ = name;
318 lexrc.printError("No name given for style: `$$Token'.");
325 docstring const style = from_utf8(subst(lexrc.getString(),
327 if (!deleteLayout(style))
328 lyxerr << "Cannot delete style `"
329 << to_utf8(style) << '\'' << endl;
330 // lexrc.printError("Cannot delete style"
337 columns_ = lexrc.getInteger();
342 switch (lexrc.getInteger()) {
343 case 1: sides_ = OneSide; break;
344 case 2: sides_ = TwoSides; break;
346 lyxerr << "Impossible number of page"
347 " sides, setting to one."
357 pagestyle_ = rtrim(lexrc.getString());
361 defaultfont_ = lyxRead(lexrc);
362 if (!defaultfont_.resolved()) {
363 lexrc.printError("Warning: defaultfont should "
364 "be fully instantiated!");
365 defaultfont_.realize(sane_font);
371 secnumdepth_ = lexrc.getInteger();
376 tocdepth_ = lexrc.getInteger();
379 // First step to support options
380 case TC_CLASSOPTIONS:
381 readClassOptions(lexrc);
385 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
390 string const feature = lexrc.getString();
392 if (lexrc.getInteger())
393 provides_.insert(feature);
395 provides_.erase(feature);
401 vector<string> const req
402 = getVectorFromString(lexrc.getString());
403 requires_.insert(req.begin(), req.end());
407 case TC_LEFTMARGIN: // left margin type
409 leftmargin_ = lexrc.getDocString();
412 case TC_RIGHTMARGIN: // right margin type
414 rightmargin_ = lexrc.getDocString();
418 docstring const name = subst(lexrc.getDocString(), '_', ' ');
419 readInsetLayout(lexrc, name);
428 case TC_TITLELATEXTYPE:
429 readTitleType(lexrc);
431 case TC_TITLELATEXNAME:
433 titlename_ = lexrc.getString();
437 string const nofloat = lexrc.getString();
438 floatlist_->erase(nofloat);
442 if (format != FORMAT)
446 if (format != FORMAT) {
447 LYXERR(Debug::TCLASS, "Converting layout file from format "
448 << format << " to " << FORMAT);
449 FileName const tempfile = FileName::tempName();
450 error = !layout2layout(filename, tempfile);
452 error = read(tempfile, rt);
453 tempfile.removeFile();
457 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
458 to_utf8(makeDisplayPath(filename.absFilename())));
463 if (defaultlayout_.empty()) {
464 lyxerr << "Error: Textclass '" << name_
465 << "' is missing a defaultstyle." << endl;
469 //Try to erase "stdinsets" from the provides_ set.
471 // Provides stdinsets 1
472 //declaration simply tells us that the standard insets have been
473 //defined. (It's found in stdinsets.inc but could also be used in
474 //user-defined files.) There isn't really any such package. So we
475 //might as well go ahead and erase it.
476 //If we do not succeed, then it was not there, which means that
477 //the textclass did not provide the definitions of the standard
478 //insets. So we need to try to load them.
479 int erased = provides_.erase("stdinsets");
481 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
484 throw ExceptionMessage(WarningException, _("Missing File"),
485 _("Could not find stdinsets.inc! This may lead to data loss!"));
487 } else if (read(tmp, MERGE)) {
488 throw ExceptionMessage(WarningException, _("Corrupt File"),
489 _("Could not read stdinsets.inc! This may lead to data loss!"));
494 min_toclevel_ = Layout::NOT_IN_TOC;
495 max_toclevel_ = Layout::NOT_IN_TOC;
496 const_iterator cit = begin();
497 const_iterator the_end = end();
498 for ( ; cit != the_end ; ++cit) {
499 int const toclevel = (*cit)->toclevel;
500 if (toclevel != Layout::NOT_IN_TOC) {
501 if (min_toclevel_ == Layout::NOT_IN_TOC)
502 min_toclevel_ = toclevel;
504 min_toclevel_ = min(min_toclevel_,
506 max_toclevel_ = max(max_toclevel_,
510 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
511 << ", maximum is " << max_toclevel_);
517 void TextClass::readTitleType(Lexer & lexrc)
519 keyword_item titleTypeTags[] = {
520 { "commandafter", TITLE_COMMAND_AFTER },
521 { "environment", TITLE_ENVIRONMENT }
524 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
526 int le = lexrc.lex();
528 case Lexer::LEX_UNDEF:
529 lexrc.printError("Unknown output type `$$Token'");
531 case TITLE_COMMAND_AFTER:
532 case TITLE_ENVIRONMENT:
533 titletype_ = static_cast<TitleLatexType>(le);
536 lyxerr << "Unhandled value " << le
537 << " in TextClass::readTitleType." << endl;
544 void TextClass::readOutputType(Lexer & lexrc)
546 keyword_item outputTypeTags[] = {
547 { "docbook", DOCBOOK },
549 { "literate", LITERATE }
552 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
554 int le = lexrc.lex();
556 case Lexer::LEX_UNDEF:
557 lexrc.printError("Unknown output type `$$Token'");
562 outputType_ = static_cast<OutputType>(le);
565 lyxerr << "Unhandled value " << le
566 << " in TextClass::readOutputType." << endl;
573 enum ClassOptionsTags {
582 void TextClass::readClassOptions(Lexer & lexrc)
584 keyword_item classOptionsTags[] = {
586 {"fontsize", CO_FONTSIZE },
587 {"header", CO_HEADER },
588 {"other", CO_OTHER },
589 {"pagestyle", CO_PAGESTYLE }
592 lexrc.pushTable(classOptionsTags, CO_END);
594 while (!getout && lexrc.isOK()) {
595 int le = lexrc.lex();
597 case Lexer::LEX_UNDEF:
598 lexrc.printError("Unknown ClassOption tag `$$Token'");
602 switch (static_cast<ClassOptionsTags>(le)) {
605 opt_fontsize_ = rtrim(lexrc.getString());
609 opt_pagestyle_ = rtrim(lexrc.getString());
613 options_ = lexrc.getString();
617 class_header_ = subst(lexrc.getString(), """, "\"");
628 enum InsetLayoutTags {
650 void TextClass::readInsetLayout(Lexer & lexrc, docstring const & name)
652 keyword_item elementTags[] = {
653 { "bgcolor", IL_BGCOLOR },
654 { "decoration", IL_DECORATION },
657 { "forceltr", IL_FORCELTR },
658 { "freespacing", IL_FREESPACING },
659 { "keepempty", IL_KEEPEMPTY },
660 { "labelfont", IL_LABELFONT },
661 { "labelstring", IL_LABELSTRING },
662 { "latexname", IL_LATEXNAME },
663 { "latexparam", IL_LATEXPARAM },
664 { "latextype", IL_LATEXTYPE },
665 { "lyxtype", IL_LYXTYPE },
666 { "multipar", IL_MULTIPAR },
667 { "needprotect", IL_NEEDPROTECT },
668 { "passthru", IL_PASSTHRU },
669 { "preamble", IL_PREAMBLE },
670 { "requires", IL_REQUIRES }
673 lexrc.pushTable(elementTags, IL_END);
676 docstring labelstring;
681 FontInfo font = inherit_font;
682 FontInfo labelfont = inherit_font;
683 ColorCode bgcolor(Color_background);
685 set<string> requires;
686 bool multipar = false;
687 bool passthru = false;
688 bool needprotect = false;
689 bool keepempty = false;
690 bool freespacing = false;
691 bool forceltr = false;
694 while (!getout && lexrc.isOK()) {
695 int le = lexrc.lex();
697 case Lexer::LEX_UNDEF:
698 lexrc.printError("Unknown InsetLayout tag `$$Token'");
702 switch (static_cast<InsetLayoutTags>(le)) {
705 lyxtype = lexrc.getString();
709 latextype = lexrc.getString();
713 labelstring = lexrc.getDocString();
717 decoration = lexrc.getString();
721 latexname = lexrc.getString();
725 latexparam = subst(lexrc.getString(), """, "\"");
728 labelfont = lyxRead(lexrc, inherit_font);
732 forceltr = lexrc.getBool();
736 multipar = lexrc.getBool();
740 passthru = lexrc.getBool();
744 keepempty = lexrc.getBool();
748 freespacing = lexrc.getBool();
752 needprotect = lexrc.getBool();
755 font = lyxRead(lexrc, inherit_font);
756 // So: define font before labelfont
761 string const token = lexrc.getString();
762 bgcolor = lcolor.getFromLyXName(token);
766 preamble = lexrc.getLongString("EndPreamble");
770 vector<string> const req
771 = getVectorFromString(lexrc.getString());
772 requires.insert(req.begin(), req.end());
781 // Here add element to list if getout == true
784 il.name = to_ascii(name);
785 il.lyxtype = lyxtype;
786 il.labelstring = labelstring;
787 il.decoration = decoration;
788 il.latextype = latextype;
789 il.latexname = latexname;
790 il.latexparam = latexparam;
791 il.multipar = multipar;
792 il.passthru = passthru;
793 il.needprotect = needprotect;
794 il.freespacing = freespacing;
795 il.forceltr = forceltr;
796 il.keepempty = keepempty;
798 // The label font is generally used as-is without
799 // any realization against a given context.
800 labelfont.realize(sane_font);
801 il.labelfont = labelfont;
802 il.bgcolor = bgcolor;
803 il.preamble = preamble;
804 il.requires = requires;
805 insetlayoutlist_[name] = il;
826 void TextClass::readFloat(Lexer & lexrc)
828 keyword_item floatTags[] = {
830 { "extension", FT_EXT },
831 { "guiname", FT_NAME },
832 { "latexbuiltin", FT_BUILTIN },
833 { "listname", FT_LISTNAME },
834 { "numberwithin", FT_WITHIN },
835 { "placement", FT_PLACEMENT },
836 { "style", FT_STYLE },
840 lexrc.pushTable(floatTags, FT_END);
849 bool builtin = false;
852 while (!getout && lexrc.isOK()) {
853 int le = lexrc.lex();
855 case Lexer::LEX_UNDEF:
856 lexrc.printError("Unknown float tag `$$Token'");
860 switch (static_cast<FloatTags>(le)) {
863 type = lexrc.getString();
864 if (floatlist_->typeExist(type)) {
865 Floating const & fl = floatlist_->getType(type);
866 placement = fl.placement();
868 within = fl.within();
871 listName = fl.listName();
872 builtin = fl.builtin();
877 name = lexrc.getString();
881 placement = lexrc.getString();
885 ext = lexrc.getString();
889 within = lexrc.getString();
890 if (within == "none")
895 style = lexrc.getString();
899 listName = lexrc.getString();
903 builtin = lexrc.getBool();
911 // Here if have a full float if getout == true
913 Floating fl(type, placement, ext, within,
914 style, name, listName, builtin);
915 floatlist_->newFloat(fl);
916 // each float has its own counter
917 counters_->newCounter(from_ascii(type), from_ascii(within),
918 docstring(), docstring());
929 CT_LABELSTRING_APPENDIX,
934 void TextClass::readCounter(Lexer & lexrc)
936 keyword_item counterTags[] = {
938 { "labelstring", CT_LABELSTRING },
939 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
941 { "within", CT_WITHIN }
944 lexrc.pushTable(counterTags, CT_END);
948 docstring labelstring;
949 docstring labelstring_appendix;
952 while (!getout && lexrc.isOK()) {
953 int le = lexrc.lex();
955 case Lexer::LEX_UNDEF:
956 lexrc.printError("Unknown counter tag `$$Token'");
960 switch (static_cast<CounterTags>(le)) {
963 name = lexrc.getDocString();
964 if (counters_->hasCounter(name))
965 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
967 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
971 within = lexrc.getDocString();
972 if (within == "none")
977 labelstring = lexrc.getDocString();
978 labelstring_appendix = labelstring;
980 case CT_LABELSTRING_APPENDIX:
982 labelstring_appendix = lexrc.getDocString();
990 // Here if have a full counter if getout == true
992 counters_->newCounter(name, within,
993 labelstring, labelstring_appendix);
999 FontInfo const & TextClass::defaultfont() const
1001 return defaultfont_;
1005 docstring const & TextClass::leftmargin() const
1011 docstring const & TextClass::rightmargin() const
1013 return rightmargin_;
1017 bool TextClass::hasLayout(docstring const & n) const
1019 docstring const name = n.empty() ? defaultLayoutName() : n;
1021 return find_if(layoutlist_.begin(), layoutlist_.end(),
1022 LayoutNamesEqual(name))
1023 != layoutlist_.end();
1028 LayoutPtr const & TextClass::operator[](docstring const & name) const
1030 BOOST_ASSERT(!name.empty());
1032 LayoutList::const_iterator cit =
1033 find_if(layoutlist_.begin(),
1035 LayoutNamesEqual(name));
1037 if (cit == layoutlist_.end()) {
1038 lyxerr << "We failed to find the layout '" << to_utf8(name)
1039 << "' in the layout list. You MUST investigate!"
1041 for (LayoutList::const_iterator it = layoutlist_.begin();
1042 it != layoutlist_.end(); ++it)
1043 lyxerr << " " << to_utf8(it->get()->name()) << endl;
1045 // we require the name to exist
1046 BOOST_ASSERT(false);
1053 bool TextClass::deleteLayout(docstring const & name)
1055 if (name == defaultLayoutName())
1058 LayoutList::iterator it =
1059 remove_if(layoutlist_.begin(), layoutlist_.end(),
1060 LayoutNamesEqual(name));
1062 LayoutList::iterator end = layoutlist_.end();
1063 bool const ret = (it != end);
1064 layoutlist_.erase(it, end);
1069 // Load textclass info if not loaded yet
1070 bool TextClass::load(string const & path) const
1075 // Read style-file, provided path is searched before the system ones
1076 FileName layout_file;
1078 layout_file = FileName(addName(path, name_ + ".layout"));
1079 if (layout_file.empty() || !layout_file.exists())
1080 layout_file = libFileSearch("layouts", name_, "layout");
1081 loaded_ = const_cast<TextClass*>(this)->read(layout_file) == 0;
1084 lyxerr << "Error reading `"
1085 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1086 << "'\n(Check `" << name_
1087 << "')\nCheck your installation and "
1088 "try Options/Reconfigure..." << endl;
1095 FloatList & TextClass::floats()
1097 return *floatlist_.get();
1101 FloatList const & TextClass::floats() const
1103 return *floatlist_.get();
1107 Counters & TextClass::counters() const
1109 return *counters_.get();
1113 // Return the layout object of an inset given by name. If the name
1114 // is not found as such, the part after the ':' is stripped off, and
1115 // searched again. In this way, an error fallback can be provided:
1116 // An erroneous 'CharStyle:badname' (e.g., after a documentclass switch)
1117 // will invoke the layout object defined by name = 'CharStyle'.
1118 // If that doesn't work either, an empty object returns (shouldn't
1119 // happen). -- Idea JMarc, comment MV
1120 InsetLayout const & TextClass::insetlayout(docstring const & name) const
1123 while (!n.empty()) {
1124 if (insetlayoutlist_.count(n) > 0)
1125 return insetlayoutlist_[n];
1126 docstring::size_type i = n.find(':');
1127 if (i == string::npos)
1131 static InsetLayout empty;
1132 empty.labelstring = from_utf8("UNDEFINED");
1133 empty.labelfont = sane_font;
1134 empty.labelfont.setColor(Color_error);
1135 empty.bgcolor = Color_error;
1140 docstring const & TextClass::defaultLayoutName() const
1142 // This really should come from the actual layout... (Lgb)
1143 return defaultlayout_;
1147 LayoutPtr const & TextClass::defaultLayout() const
1149 return operator[](defaultLayoutName());
1153 string const & TextClass::name() const
1159 string const & TextClass::latexname() const
1161 const_cast<TextClass*>(this)->load();
1166 string const & TextClass::description() const
1168 return description_;
1172 string const & TextClass::opt_fontsize() const
1174 return opt_fontsize_;
1178 string const & TextClass::opt_pagestyle() const
1180 return opt_pagestyle_;
1184 string const & TextClass::options() const
1190 string const & TextClass::class_header() const
1192 return class_header_;
1196 string const & TextClass::pagestyle() const
1202 docstring const & TextClass::preamble() const
1208 PageSides TextClass::sides() const
1214 int TextClass::secnumdepth() const
1216 return secnumdepth_;
1220 int TextClass::tocdepth() const
1226 OutputType TextClass::outputType() const
1232 bool TextClass::provides(string const & p) const
1234 return provides_.find(p) != provides_.end();
1238 unsigned int TextClass::columns() const
1244 TitleLatexType TextClass::titletype() const
1250 string const & TextClass::titlename() const
1256 int TextClass::size() const
1258 return layoutlist_.size();
1262 int TextClass::min_toclevel() const
1264 return min_toclevel_;
1268 int TextClass::max_toclevel() const
1270 return max_toclevel_;
1274 bool TextClass::hasTocLevels() const
1276 return min_toclevel_ != Layout::NOT_IN_TOC;
1280 ostream & operator<<(ostream & os, PageSides p)