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/lstrings.h"
32 #include "support/FileName.h"
33 #include "support/filetools.h"
34 #include "support/os.h"
39 using namespace lyx::support;
45 class LayoutNamesEqual : public unary_function<LayoutPtr, bool> {
47 LayoutNamesEqual(docstring const & name)
50 bool operator()(LayoutPtr const & c) const
52 return c->name() == name_;
62 bool layout2layout(FileName const & filename, FileName const & tempfile)
64 FileName const script = libFileSearch("scripts", "layout2layout.py");
66 lyxerr << "Could not find layout conversion "
67 "script layout2layout.py." << endl;
71 ostringstream command;
72 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
73 << ' ' << quoteName(filename.toFilesystemEncoding())
74 << ' ' << quoteName(tempfile.toFilesystemEncoding());
75 string const command_str = command.str();
77 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
80 runCommand(command_str);
82 lyxerr << "Could not run layout conversion "
83 "script layout2layout.py." << endl;
90 std::string translateRT(TextClass::ReadType rt)
93 case TextClass::BASECLASS:
95 case TextClass::MERGE:
97 case TextClass::MODULE:
107 TextClass::TextClass(string const & fn, string const & cln,
108 string const & desc, bool texClassAvail )
109 : name_(fn), latexname_(cln), description_(desc),
110 floatlist_(new FloatList), counters_(new Counters),
111 texClassAvail_(texClassAvail)
119 pagestyle_ = "default";
120 defaultfont_ = sane_font;
121 opt_fontsize_ = "10|11|12";
122 opt_pagestyle_ = "empty|plain|headings|fancy";
123 titletype_ = TITLE_COMMAND_AFTER;
124 titlename_ = "maketitle";
129 bool TextClass::isTeXClassAvailable() const
131 return texClassAvail_;
135 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
137 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
138 if (!lay.read(lexrc, *this)) {
140 lay.resfont = lay.font;
141 lay.resfont.realize(defaultfont());
142 lay.reslabelfont = lay.labelfont;
143 lay.reslabelfont.realize(defaultfont());
144 return false; // no errors
146 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
180 // Reads a textclass structure from file.
181 bool TextClass::read(FileName const & filename, ReadType rt)
183 if (!filename.isReadableFile()) {
184 lyxerr << "Cannot read layout file `" << filename << "'."
189 keyword_item textClassTags[] = {
190 { "classoptions", TC_CLASSOPTIONS },
191 { "columns", TC_COLUMNS },
192 { "counter", TC_COUNTER },
193 { "defaultfont", TC_DEFAULTFONT },
194 { "defaultstyle", TC_DEFAULTSTYLE },
195 { "environment", TC_ENVIRONMENT },
196 { "float", TC_FLOAT },
197 { "format", TC_FORMAT },
198 { "input", TC_INPUT },
199 { "insetlayout", TC_INSETLAYOUT },
200 { "leftmargin", TC_LEFTMARGIN },
201 { "nofloat", TC_NOFLOAT },
202 { "nostyle", TC_NOSTYLE },
203 { "outputtype", TC_OUTPUTTYPE },
204 { "pagestyle", TC_PAGESTYLE },
205 { "preamble", TC_PREAMBLE },
206 { "provides", TC_PROVIDES },
207 { "requires", TC_REQUIRES },
208 { "rightmargin", TC_RIGHTMARGIN },
209 { "secnumdepth", TC_SECNUMDEPTH },
210 { "sides", TC_SIDES },
211 { "style", TC_STYLE },
212 { "titlelatexname", TC_TITLELATEXNAME },
213 { "titlelatextype", TC_TITLELATEXTYPE },
214 { "tocdepth", TC_TOCDEPTH }
217 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
218 to_utf8(makeDisplayPath(filename.absFilename())));
220 Lexer lexrc(textClassTags,
221 sizeof(textClassTags) / sizeof(textClassTags[0]));
223 lexrc.setFile(filename);
224 bool error = !lexrc.isOK();
226 // Format of files before the 'Format' tag was introduced
230 while (lexrc.isOK() && !error) {
231 int le = lexrc.lex();
234 case Lexer::LEX_FEOF:
237 case Lexer::LEX_UNDEF:
238 lexrc.printError("Unknown TextClass tag `$$Token'");
246 switch (static_cast<TextClassTags>(le)) {
250 format = lexrc.getInteger();
253 case TC_OUTPUTTYPE: // output type definition
254 readOutputType(lexrc);
257 case TC_INPUT: // Include file
259 string const inc = lexrc.getString();
260 FileName tmp = libFileSearch("layouts", inc,
264 lexrc.printError("Could not find input file: " + inc);
266 } else if (read(tmp, MERGE)) {
267 lexrc.printError("Error reading input"
268 "file: " + tmp.absFilename());
274 case TC_DEFAULTSTYLE:
276 docstring const name = from_utf8(subst(lexrc.getString(),
278 defaultlayout_ = name;
285 docstring const name = from_utf8(subst(lexrc.getString(),
288 string s = "Could not read name for style: `$$Token' "
289 + lexrc.getString() + " is probably not valid UTF-8!";
290 lexrc.printError(s.c_str());
292 error = readStyle(lexrc, lay);
293 } else if (hasLayout(name)) {
294 Layout * lay = operator[](name).get();
295 error = readStyle(lexrc, *lay);
299 if (le == TC_ENVIRONMENT)
300 lay.is_environment = true;
301 error = readStyle(lexrc, lay);
303 layoutlist_.push_back(
304 boost::shared_ptr<Layout>(new Layout(lay))
307 if (defaultlayout_.empty()) {
308 // We do not have a default
309 // layout yet, so we choose
310 // the first layout we
312 defaultlayout_ = name;
317 lexrc.printError("No name given for style: `$$Token'.");
324 docstring const style = from_utf8(subst(lexrc.getString(),
326 if (!deleteLayout(style))
327 lyxerr << "Cannot delete style `"
328 << to_utf8(style) << '\'' << endl;
329 // lexrc.printError("Cannot delete style"
336 columns_ = lexrc.getInteger();
341 switch (lexrc.getInteger()) {
342 case 1: sides_ = OneSide; break;
343 case 2: sides_ = TwoSides; break;
345 lyxerr << "Impossible number of page"
346 " sides, setting to one."
356 pagestyle_ = rtrim(lexrc.getString());
360 defaultfont_ = lyxRead(lexrc);
361 if (!defaultfont_.resolved()) {
362 lexrc.printError("Warning: defaultfont should "
363 "be fully instantiated!");
364 defaultfont_.realize(sane_font);
370 secnumdepth_ = lexrc.getInteger();
375 tocdepth_ = lexrc.getInteger();
378 // First step to support options
379 case TC_CLASSOPTIONS:
380 readClassOptions(lexrc);
384 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
389 string const feature = lexrc.getString();
391 if (lexrc.getInteger())
392 provides_.insert(feature);
394 provides_.erase(feature);
400 vector<string> const req
401 = getVectorFromString(lexrc.getString());
402 requires_.insert(req.begin(), req.end());
406 case TC_LEFTMARGIN: // left margin type
408 leftmargin_ = lexrc.getDocString();
411 case TC_RIGHTMARGIN: // right margin type
413 rightmargin_ = lexrc.getDocString();
417 docstring const name = subst(lexrc.getDocString(), '_', ' ');
418 readInsetLayout(lexrc, name);
427 case TC_TITLELATEXTYPE:
428 readTitleType(lexrc);
430 case TC_TITLELATEXNAME:
432 titlename_ = lexrc.getString();
436 string const nofloat = lexrc.getString();
437 floatlist_->erase(nofloat);
441 if (format != FORMAT)
445 if (format != FORMAT) {
446 LYXERR(Debug::TCLASS, "Converting layout file from format "
447 << format << " to " << FORMAT);
448 FileName const tempfile = FileName::tempName();
449 error = !layout2layout(filename, tempfile);
451 error = read(tempfile, rt);
452 tempfile.removeFile();
456 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
457 to_utf8(makeDisplayPath(filename.absFilename())));
462 if (defaultlayout_.empty()) {
463 lyxerr << "Error: Textclass '" << name_
464 << "' is missing a defaultstyle." << endl;
468 //Try to erase "stdinsets" from the provides_ set.
470 // Provides stdinsets 1
471 //declaration simply tells us that the standard insets have been
472 //defined. (It's found in stdinsets.inc but could also be used in
473 //user-defined files.) There isn't really any such package. So we
474 //might as well go ahead and erase it.
475 //If we do not succeed, then it was not there, which means that
476 //the textclass did not provide the definitions of the standard
477 //insets. So we need to try to load them.
478 int erased = provides_.erase("stdinsets");
480 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
483 frontend::Alert::warning(_("Missing File"),
484 _("Could not find stdinsets.inc! This may lead to data loss!"));
486 } else if (read(tmp, MERGE)) {
487 frontend::Alert::warning(_("Corrupt File"),
488 _("Could not read stdinsets.inc! This may lead to data loss!"));
493 min_toclevel_ = Layout::NOT_IN_TOC;
494 max_toclevel_ = Layout::NOT_IN_TOC;
495 const_iterator cit = begin();
496 const_iterator the_end = end();
497 for ( ; cit != the_end ; ++cit) {
498 int const toclevel = (*cit)->toclevel;
499 if (toclevel != Layout::NOT_IN_TOC) {
500 if (min_toclevel_ == Layout::NOT_IN_TOC)
501 min_toclevel_ = toclevel;
503 min_toclevel_ = min(min_toclevel_,
505 max_toclevel_ = max(max_toclevel_,
509 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
510 << ", maximum is " << max_toclevel_);
516 void TextClass::readTitleType(Lexer & lexrc)
518 keyword_item titleTypeTags[] = {
519 { "commandafter", TITLE_COMMAND_AFTER },
520 { "environment", TITLE_ENVIRONMENT }
523 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
525 int le = lexrc.lex();
527 case Lexer::LEX_UNDEF:
528 lexrc.printError("Unknown output type `$$Token'");
530 case TITLE_COMMAND_AFTER:
531 case TITLE_ENVIRONMENT:
532 titletype_ = static_cast<TitleLatexType>(le);
535 lyxerr << "Unhandled value " << le
536 << " in TextClass::readTitleType." << endl;
543 void TextClass::readOutputType(Lexer & lexrc)
545 keyword_item outputTypeTags[] = {
546 { "docbook", DOCBOOK },
548 { "literate", LITERATE }
551 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
553 int le = lexrc.lex();
555 case Lexer::LEX_UNDEF:
556 lexrc.printError("Unknown output type `$$Token'");
561 outputType_ = static_cast<OutputType>(le);
564 lyxerr << "Unhandled value " << le
565 << " in TextClass::readOutputType." << endl;
572 enum ClassOptionsTags {
581 void TextClass::readClassOptions(Lexer & lexrc)
583 keyword_item classOptionsTags[] = {
585 {"fontsize", CO_FONTSIZE },
586 {"header", CO_HEADER },
587 {"other", CO_OTHER },
588 {"pagestyle", CO_PAGESTYLE }
591 lexrc.pushTable(classOptionsTags, CO_END);
593 while (!getout && lexrc.isOK()) {
594 int le = lexrc.lex();
596 case Lexer::LEX_UNDEF:
597 lexrc.printError("Unknown ClassOption tag `$$Token'");
601 switch (static_cast<ClassOptionsTags>(le)) {
604 opt_fontsize_ = rtrim(lexrc.getString());
608 opt_pagestyle_ = rtrim(lexrc.getString());
612 options_ = lexrc.getString();
616 class_header_ = subst(lexrc.getString(), """, "\"");
627 enum InsetLayoutTags {
649 void TextClass::readInsetLayout(Lexer & lexrc, docstring const & name)
651 keyword_item elementTags[] = {
652 { "bgcolor", IL_BGCOLOR },
653 { "decoration", IL_DECORATION },
656 { "forceltr", IL_FORCELTR },
657 { "freespacing", IL_FREESPACING },
658 { "keepempty", IL_KEEPEMPTY },
659 { "labelfont", IL_LABELFONT },
660 { "labelstring", IL_LABELSTRING },
661 { "latexname", IL_LATEXNAME },
662 { "latexparam", IL_LATEXPARAM },
663 { "latextype", IL_LATEXTYPE },
664 { "lyxtype", IL_LYXTYPE },
665 { "multipar", IL_MULTIPAR },
666 { "needprotect", IL_NEEDPROTECT },
667 { "passthru", IL_PASSTHRU },
668 { "preamble", IL_PREAMBLE },
669 { "requires", IL_REQUIRES }
672 lexrc.pushTable(elementTags, IL_END);
675 docstring labelstring;
680 FontInfo font = inherit_font;
681 FontInfo labelfont = inherit_font;
682 ColorCode bgcolor(Color_background);
684 set<string> requires;
685 bool multipar = false;
686 bool passthru = false;
687 bool needprotect = false;
688 bool keepempty = false;
689 bool freespacing = false;
690 bool forceltr = false;
693 while (!getout && lexrc.isOK()) {
694 int le = lexrc.lex();
696 case Lexer::LEX_UNDEF:
697 lexrc.printError("Unknown InsetLayout tag `$$Token'");
701 switch (static_cast<InsetLayoutTags>(le)) {
704 lyxtype = lexrc.getString();
708 latextype = lexrc.getString();
712 labelstring = lexrc.getDocString();
716 decoration = lexrc.getString();
720 latexname = lexrc.getString();
724 latexparam = subst(lexrc.getString(), """, "\"");
727 labelfont = lyxRead(lexrc, inherit_font);
731 forceltr = lexrc.getBool();
735 multipar = lexrc.getBool();
739 passthru = lexrc.getBool();
743 keepempty = lexrc.getBool();
747 freespacing = lexrc.getBool();
751 needprotect = lexrc.getBool();
754 font = lyxRead(lexrc, inherit_font);
755 // So: define font before labelfont
760 string const token = lexrc.getString();
761 bgcolor = lcolor.getFromLyXName(token);
765 preamble = lexrc.getLongString("EndPreamble");
769 vector<string> const req
770 = getVectorFromString(lexrc.getString());
771 requires.insert(req.begin(), req.end());
780 // Here add element to list if getout == true
783 il.name = to_ascii(name);
784 il.lyxtype = lyxtype;
785 il.labelstring = labelstring;
786 il.decoration = decoration;
787 il.latextype = latextype;
788 il.latexname = latexname;
789 il.latexparam = latexparam;
790 il.multipar = multipar;
791 il.passthru = passthru;
792 il.needprotect = needprotect;
793 il.freespacing = freespacing;
794 il.forceltr = forceltr;
795 il.keepempty = keepempty;
797 // The label font is generally used as-is without
798 // any realization against a given context.
799 labelfont.realize(sane_font);
800 il.labelfont = labelfont;
801 il.bgcolor = bgcolor;
802 il.preamble = preamble;
803 il.requires = requires;
804 insetlayoutlist_[name] = il;
825 void TextClass::readFloat(Lexer & lexrc)
827 keyword_item floatTags[] = {
829 { "extension", FT_EXT },
830 { "guiname", FT_NAME },
831 { "latexbuiltin", FT_BUILTIN },
832 { "listname", FT_LISTNAME },
833 { "numberwithin", FT_WITHIN },
834 { "placement", FT_PLACEMENT },
835 { "style", FT_STYLE },
839 lexrc.pushTable(floatTags, FT_END);
848 bool builtin = false;
851 while (!getout && lexrc.isOK()) {
852 int le = lexrc.lex();
854 case Lexer::LEX_UNDEF:
855 lexrc.printError("Unknown float tag `$$Token'");
859 switch (static_cast<FloatTags>(le)) {
862 type = lexrc.getString();
863 if (floatlist_->typeExist(type)) {
864 Floating const & fl = floatlist_->getType(type);
865 placement = fl.placement();
867 within = fl.within();
870 listName = fl.listName();
871 builtin = fl.builtin();
876 name = lexrc.getString();
880 placement = lexrc.getString();
884 ext = lexrc.getString();
888 within = lexrc.getString();
889 if (within == "none")
894 style = lexrc.getString();
898 listName = lexrc.getString();
902 builtin = lexrc.getBool();
910 // Here if have a full float if getout == true
912 Floating fl(type, placement, ext, within,
913 style, name, listName, builtin);
914 floatlist_->newFloat(fl);
915 // each float has its own counter
916 counters_->newCounter(from_ascii(type), from_ascii(within),
917 docstring(), docstring());
928 CT_LABELSTRING_APPENDIX,
933 void TextClass::readCounter(Lexer & lexrc)
935 keyword_item counterTags[] = {
937 { "labelstring", CT_LABELSTRING },
938 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
940 { "within", CT_WITHIN }
943 lexrc.pushTable(counterTags, CT_END);
947 docstring labelstring;
948 docstring labelstring_appendix;
951 while (!getout && lexrc.isOK()) {
952 int le = lexrc.lex();
954 case Lexer::LEX_UNDEF:
955 lexrc.printError("Unknown counter tag `$$Token'");
959 switch (static_cast<CounterTags>(le)) {
962 name = lexrc.getDocString();
963 if (counters_->hasCounter(name))
964 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
966 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
970 within = lexrc.getDocString();
971 if (within == "none")
976 labelstring = lexrc.getDocString();
977 labelstring_appendix = labelstring;
979 case CT_LABELSTRING_APPENDIX:
981 labelstring_appendix = lexrc.getDocString();
989 // Here if have a full counter if getout == true
991 counters_->newCounter(name, within,
992 labelstring, labelstring_appendix);
998 FontInfo const & TextClass::defaultfont() const
1000 return defaultfont_;
1004 docstring const & TextClass::leftmargin() const
1010 docstring const & TextClass::rightmargin() const
1012 return rightmargin_;
1016 bool TextClass::hasLayout(docstring const & n) const
1018 docstring const name = n.empty() ? defaultLayoutName() : n;
1020 return find_if(layoutlist_.begin(), layoutlist_.end(),
1021 LayoutNamesEqual(name))
1022 != layoutlist_.end();
1027 LayoutPtr const & TextClass::operator[](docstring const & name) const
1029 BOOST_ASSERT(!name.empty());
1031 LayoutList::const_iterator cit =
1032 find_if(layoutlist_.begin(),
1034 LayoutNamesEqual(name));
1036 if (cit == layoutlist_.end()) {
1037 lyxerr << "We failed to find the layout '" << to_utf8(name)
1038 << "' in the layout list. You MUST investigate!"
1040 for (LayoutList::const_iterator it = layoutlist_.begin();
1041 it != layoutlist_.end(); ++it)
1042 lyxerr << " " << to_utf8(it->get()->name()) << endl;
1044 // we require the name to exist
1045 BOOST_ASSERT(false);
1052 bool TextClass::deleteLayout(docstring const & name)
1054 if (name == defaultLayoutName())
1057 LayoutList::iterator it =
1058 remove_if(layoutlist_.begin(), layoutlist_.end(),
1059 LayoutNamesEqual(name));
1061 LayoutList::iterator end = layoutlist_.end();
1062 bool const ret = (it != end);
1063 layoutlist_.erase(it, end);
1068 // Load textclass info if not loaded yet
1069 bool TextClass::load(string const & path) const
1074 // Read style-file, provided path is searched before the system ones
1075 FileName layout_file;
1077 layout_file = FileName(addName(path, name_ + ".layout"));
1078 if (layout_file.empty() || !layout_file.exists())
1079 layout_file = libFileSearch("layouts", name_, "layout");
1080 loaded_ = const_cast<TextClass*>(this)->read(layout_file) == 0;
1083 lyxerr << "Error reading `"
1084 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1085 << "'\n(Check `" << name_
1086 << "')\nCheck your installation and "
1087 "try Options/Reconfigure..." << endl;
1094 FloatList & TextClass::floats()
1096 return *floatlist_.get();
1100 FloatList const & TextClass::floats() const
1102 return *floatlist_.get();
1106 Counters & TextClass::counters() const
1108 return *counters_.get();
1112 // Return the layout object of an inset given by name. If the name
1113 // is not found as such, the part after the ':' is stripped off, and
1114 // searched again. In this way, an error fallback can be provided:
1115 // An erroneous 'CharStyle:badname' (e.g., after a documentclass switch)
1116 // will invoke the layout object defined by name = 'CharStyle'.
1117 // If that doesn't work either, an empty object returns (shouldn't
1118 // happen). -- Idea JMarc, comment MV
1119 InsetLayout const & TextClass::insetlayout(docstring const & name) const
1122 while (!n.empty()) {
1123 if (insetlayoutlist_.count(n) > 0)
1124 return insetlayoutlist_[n];
1125 docstring::size_type i = n.find(':');
1126 if (i == string::npos)
1130 static InsetLayout empty;
1131 empty.labelstring = from_utf8("UNDEFINED");
1132 empty.labelfont = sane_font;
1133 empty.labelfont.setColor(Color_error);
1134 empty.bgcolor = Color_error;
1139 docstring const & TextClass::defaultLayoutName() const
1141 // This really should come from the actual layout... (Lgb)
1142 return defaultlayout_;
1146 LayoutPtr const & TextClass::defaultLayout() const
1148 return operator[](defaultLayoutName());
1152 string const & TextClass::name() const
1158 string const & TextClass::latexname() const
1160 const_cast<TextClass*>(this)->load();
1165 string const & TextClass::description() const
1167 return description_;
1171 string const & TextClass::opt_fontsize() const
1173 return opt_fontsize_;
1177 string const & TextClass::opt_pagestyle() const
1179 return opt_pagestyle_;
1183 string const & TextClass::options() const
1189 string const & TextClass::class_header() const
1191 return class_header_;
1195 string const & TextClass::pagestyle() const
1201 docstring const & TextClass::preamble() const
1207 PageSides TextClass::sides() const
1213 int TextClass::secnumdepth() const
1215 return secnumdepth_;
1219 int TextClass::tocdepth() const
1225 OutputType TextClass::outputType() const
1231 bool TextClass::provides(string const & p) const
1233 return provides_.find(p) != provides_.end();
1237 unsigned int TextClass::columns() const
1243 TitleLatexType TextClass::titletype() const
1249 string const & TextClass::titlename() const
1255 int TextClass::size() const
1257 return layoutlist_.size();
1261 int TextClass::min_toclevel() const
1263 return min_toclevel_;
1267 int TextClass::max_toclevel() const
1269 return max_toclevel_;
1273 bool TextClass::hasTocLevels() const
1275 return min_toclevel_ != Layout::NOT_IN_TOC;
1279 ostream & operator<<(ostream & os, PageSides p)