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:
105 TextClass::TextClass(string const & fn, string const & cln,
106 string const & desc, bool texClassAvail )
107 : name_(fn), latexname_(cln), description_(desc),
108 floatlist_(new FloatList), counters_(new Counters),
109 texClassAvail_(texClassAvail)
117 pagestyle_ = "default";
118 defaultfont_ = sane_font;
119 opt_fontsize_ = "10|11|12";
120 opt_pagestyle_ = "empty|plain|headings|fancy";
121 titletype_ = TITLE_COMMAND_AFTER;
122 titlename_ = "maketitle";
127 bool TextClass::isTeXClassAvailable() const
129 return texClassAvail_;
133 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
135 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
136 if (!lay.read(lexrc, *this)) {
138 lay.resfont = lay.font;
139 lay.resfont.realize(defaultfont());
140 lay.reslabelfont = lay.labelfont;
141 lay.reslabelfont.realize(defaultfont());
142 return false; // no errors
144 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
178 // Reads a textclass structure from file.
179 bool TextClass::read(FileName const & filename, ReadType rt)
181 if (!filename.isReadableFile()) {
182 lyxerr << "Cannot read layout file `" << filename << "'."
187 keyword_item textClassTags[] = {
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 }
215 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
216 to_utf8(makeDisplayPath(filename.absFilename())));
218 Lexer lexrc(textClassTags,
219 sizeof(textClassTags) / sizeof(textClassTags[0]));
221 lexrc.setFile(filename);
222 bool error = !lexrc.isOK();
224 // Format of files before the 'Format' tag was introduced
228 while (lexrc.isOK() && !error) {
229 int le = lexrc.lex();
232 case Lexer::LEX_FEOF:
235 case Lexer::LEX_UNDEF:
236 lexrc.printError("Unknown TextClass tag `$$Token'");
244 switch (static_cast<TextClassTags>(le)) {
248 format = lexrc.getInteger();
251 case TC_OUTPUTTYPE: // output type definition
252 readOutputType(lexrc);
255 case TC_INPUT: // Include file
257 string const inc = lexrc.getString();
258 FileName tmp = libFileSearch("layouts", inc,
262 lexrc.printError("Could not find input file: " + inc);
264 } else if (read(tmp, MERGE)) {
265 lexrc.printError("Error reading input"
266 "file: " + tmp.absFilename());
272 case TC_DEFAULTSTYLE:
274 docstring const name = from_utf8(subst(lexrc.getString(),
276 defaultlayout_ = name;
283 docstring const name = from_utf8(subst(lexrc.getString(),
286 string s = "Could not read name for style: `$$Token' "
287 + lexrc.getString() + " is probably not valid UTF-8!";
288 lexrc.printError(s.c_str());
290 error = readStyle(lexrc, lay);
291 } else if (hasLayout(name)) {
292 Layout * lay = operator[](name).get();
293 error = readStyle(lexrc, *lay);
297 if (le == TC_ENVIRONMENT)
298 lay.is_environment = true;
299 error = readStyle(lexrc, lay);
301 layoutlist_.push_back(
302 boost::shared_ptr<Layout>(new Layout(lay))
305 if (defaultlayout_.empty()) {
306 // We do not have a default
307 // layout yet, so we choose
308 // the first layout we
310 defaultlayout_ = name;
315 lexrc.printError("No name given for style: `$$Token'.");
322 docstring const style = from_utf8(subst(lexrc.getString(),
324 if (!deleteLayout(style))
325 lyxerr << "Cannot delete style `"
326 << to_utf8(style) << '\'' << endl;
327 // lexrc.printError("Cannot delete style"
334 columns_ = lexrc.getInteger();
339 switch (lexrc.getInteger()) {
340 case 1: sides_ = OneSide; break;
341 case 2: sides_ = TwoSides; break;
343 lyxerr << "Impossible number of page"
344 " sides, setting to one."
354 pagestyle_ = rtrim(lexrc.getString());
358 defaultfont_ = lyxRead(lexrc);
359 if (!defaultfont_.resolved()) {
360 lexrc.printError("Warning: defaultfont should "
361 "be fully instantiated!");
362 defaultfont_.realize(sane_font);
368 secnumdepth_ = lexrc.getInteger();
373 tocdepth_ = lexrc.getInteger();
376 // First step to support options
377 case TC_CLASSOPTIONS:
378 readClassOptions(lexrc);
382 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
387 string const feature = lexrc.getString();
389 if (lexrc.getInteger())
390 provides_.insert(feature);
392 provides_.erase(feature);
398 vector<string> const req
399 = getVectorFromString(lexrc.getString());
400 requires_.insert(req.begin(), req.end());
404 case TC_LEFTMARGIN: // left margin type
406 leftmargin_ = lexrc.getDocString();
409 case TC_RIGHTMARGIN: // right margin type
411 rightmargin_ = lexrc.getDocString();
415 docstring const name = subst(lexrc.getDocString(), '_', ' ');
416 readInsetLayout(lexrc, name);
425 case TC_TITLELATEXTYPE:
426 readTitleType(lexrc);
428 case TC_TITLELATEXNAME:
430 titlename_ = lexrc.getString();
434 string const nofloat = lexrc.getString();
435 floatlist_->erase(nofloat);
439 if (format != FORMAT)
443 if (format != FORMAT) {
444 LYXERR(Debug::TCLASS, "Converting layout file from format "
445 << format << " to " << FORMAT);
446 FileName const tempfile = FileName::tempName();
447 error = !layout2layout(filename, tempfile);
449 error = read(tempfile, rt);
450 tempfile.removeFile();
454 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
455 to_utf8(makeDisplayPath(filename.absFilename())));
460 if (defaultlayout_.empty()) {
461 lyxerr << "Error: Textclass '" << name_
462 << "' is missing a defaultstyle." << endl;
466 //Try to erase "stdinsets" from the provides_ set.
468 // Provides stdinsets 1
469 //declaration simply tells us that the standard insets have been
470 //defined. (It's found in stdinsets.inc but could also be used in
471 //user-defined files.) There isn't really any such package. So we
472 //might as well go ahead and erase it.
473 //If we do not succeed, then it was not there, which means that
474 //the textclass did not provide the definitions of the standard
475 //insets. So we need to try to load them.
476 int erased = provides_.erase("stdinsets");
478 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
481 frontend::Alert::warning(_("Missing File"),
482 _("Could not find stdinsets.inc! This may lead to data loss!"));
484 } else if (read(tmp, MERGE)) {
485 frontend::Alert::warning(_("Corrupt File"),
486 _("Could not read stdinsets.inc! This may lead to data loss!"));
491 min_toclevel_ = Layout::NOT_IN_TOC;
492 max_toclevel_ = Layout::NOT_IN_TOC;
493 const_iterator cit = begin();
494 const_iterator the_end = end();
495 for ( ; cit != the_end ; ++cit) {
496 int const toclevel = (*cit)->toclevel;
497 if (toclevel != Layout::NOT_IN_TOC) {
498 if (min_toclevel_ == Layout::NOT_IN_TOC)
499 min_toclevel_ = toclevel;
501 min_toclevel_ = min(min_toclevel_,
503 max_toclevel_ = max(max_toclevel_,
507 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
508 << ", maximum is " << max_toclevel_);
514 void TextClass::readTitleType(Lexer & lexrc)
516 keyword_item titleTypeTags[] = {
517 { "commandafter", TITLE_COMMAND_AFTER },
518 { "environment", TITLE_ENVIRONMENT }
521 PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
523 int le = lexrc.lex();
525 case Lexer::LEX_UNDEF:
526 lexrc.printError("Unknown output type `$$Token'");
528 case TITLE_COMMAND_AFTER:
529 case TITLE_ENVIRONMENT:
530 titletype_ = static_cast<TitleLatexType>(le);
533 lyxerr << "Unhandled value " << le
534 << " in TextClass::readTitleType." << endl;
541 void TextClass::readOutputType(Lexer & lexrc)
543 keyword_item outputTypeTags[] = {
544 { "docbook", DOCBOOK },
546 { "literate", LITERATE }
549 PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
551 int le = lexrc.lex();
553 case Lexer::LEX_UNDEF:
554 lexrc.printError("Unknown output type `$$Token'");
559 outputType_ = static_cast<OutputType>(le);
562 lyxerr << "Unhandled value " << le
563 << " in TextClass::readOutputType." << endl;
570 enum ClassOptionsTags {
579 void TextClass::readClassOptions(Lexer & lexrc)
581 keyword_item classOptionsTags[] = {
583 {"fontsize", CO_FONTSIZE },
584 {"header", CO_HEADER },
585 {"other", CO_OTHER },
586 {"pagestyle", CO_PAGESTYLE }
589 lexrc.pushTable(classOptionsTags, CO_END);
591 while (!getout && lexrc.isOK()) {
592 int le = lexrc.lex();
594 case Lexer::LEX_UNDEF:
595 lexrc.printError("Unknown ClassOption tag `$$Token'");
599 switch (static_cast<ClassOptionsTags>(le)) {
602 opt_fontsize_ = rtrim(lexrc.getString());
606 opt_pagestyle_ = rtrim(lexrc.getString());
610 options_ = lexrc.getString();
614 class_header_ = subst(lexrc.getString(), """, "\"");
625 enum InsetLayoutTags {
647 void TextClass::readInsetLayout(Lexer & lexrc, docstring const & name)
649 keyword_item elementTags[] = {
650 { "bgcolor", IL_BGCOLOR },
651 { "decoration", IL_DECORATION },
654 { "forceltr", IL_FORCELTR },
655 { "freespacing", IL_FREESPACING },
656 { "keepempty", IL_KEEPEMPTY },
657 { "labelfont", IL_LABELFONT },
658 { "labelstring", IL_LABELSTRING },
659 { "latexname", IL_LATEXNAME },
660 { "latexparam", IL_LATEXPARAM },
661 { "latextype", IL_LATEXTYPE },
662 { "lyxtype", IL_LYXTYPE },
663 { "multipar", IL_MULTIPAR },
664 { "needprotect", IL_NEEDPROTECT },
665 { "passthru", IL_PASSTHRU },
666 { "preamble", IL_PREAMBLE },
667 { "requires", IL_REQUIRES }
670 lexrc.pushTable(elementTags, IL_END);
673 docstring labelstring;
678 FontInfo font = inherit_font;
679 FontInfo labelfont = inherit_font;
680 ColorCode bgcolor(Color_background);
682 set<string> requires;
683 bool multipar = false;
684 bool passthru = false;
685 bool needprotect = false;
686 bool keepempty = false;
687 bool freespacing = false;
688 bool forceltr = false;
691 while (!getout && lexrc.isOK()) {
692 int le = lexrc.lex();
694 case Lexer::LEX_UNDEF:
695 lexrc.printError("Unknown InsetLayout tag `$$Token'");
699 switch (static_cast<InsetLayoutTags>(le)) {
702 lyxtype = lexrc.getString();
706 latextype = lexrc.getString();
710 labelstring = lexrc.getDocString();
714 decoration = lexrc.getString();
718 latexname = lexrc.getString();
722 latexparam = subst(lexrc.getString(), """, "\"");
725 labelfont = lyxRead(lexrc, inherit_font);
729 forceltr = lexrc.getBool();
733 multipar = lexrc.getBool();
737 passthru = lexrc.getBool();
741 keepempty = lexrc.getBool();
745 freespacing = lexrc.getBool();
749 needprotect = lexrc.getBool();
752 font = lyxRead(lexrc, inherit_font);
753 // So: define font before labelfont
758 string const token = lexrc.getString();
759 bgcolor = lcolor.getFromLyXName(token);
763 preamble = lexrc.getLongString("EndPreamble");
767 vector<string> const req
768 = getVectorFromString(lexrc.getString());
769 requires.insert(req.begin(), req.end());
778 // Here add element to list if getout == true
781 il.name = to_ascii(name);
782 il.lyxtype = lyxtype;
783 il.labelstring = labelstring;
784 il.decoration = decoration;
785 il.latextype = latextype;
786 il.latexname = latexname;
787 il.latexparam = latexparam;
788 il.multipar = multipar;
789 il.passthru = passthru;
790 il.needprotect = needprotect;
791 il.freespacing = freespacing;
792 il.forceltr = forceltr;
793 il.keepempty = keepempty;
795 // The label font is generally used as-is without
796 // any realization against a given context.
797 labelfont.realize(sane_font);
798 il.labelfont = labelfont;
799 il.bgcolor = bgcolor;
800 il.preamble = preamble;
801 il.requires = requires;
802 insetlayoutlist_[name] = il;
823 void TextClass::readFloat(Lexer & lexrc)
825 keyword_item floatTags[] = {
827 { "extension", FT_EXT },
828 { "guiname", FT_NAME },
829 { "latexbuiltin", FT_BUILTIN },
830 { "listname", FT_LISTNAME },
831 { "numberwithin", FT_WITHIN },
832 { "placement", FT_PLACEMENT },
833 { "style", FT_STYLE },
837 lexrc.pushTable(floatTags, FT_END);
846 bool builtin = false;
849 while (!getout && lexrc.isOK()) {
850 int le = lexrc.lex();
852 case Lexer::LEX_UNDEF:
853 lexrc.printError("Unknown float tag `$$Token'");
857 switch (static_cast<FloatTags>(le)) {
860 type = lexrc.getString();
861 if (floatlist_->typeExist(type)) {
862 Floating const & fl = floatlist_->getType(type);
863 placement = fl.placement();
865 within = fl.within();
868 listName = fl.listName();
869 builtin = fl.builtin();
874 name = lexrc.getString();
878 placement = lexrc.getString();
882 ext = lexrc.getString();
886 within = lexrc.getString();
887 if (within == "none")
892 style = lexrc.getString();
896 listName = lexrc.getString();
900 builtin = lexrc.getBool();
908 // Here if have a full float if getout == true
910 Floating fl(type, placement, ext, within,
911 style, name, listName, builtin);
912 floatlist_->newFloat(fl);
913 // each float has its own counter
914 counters_->newCounter(from_ascii(type), from_ascii(within),
915 docstring(), docstring());
926 CT_LABELSTRING_APPENDIX,
931 void TextClass::readCounter(Lexer & lexrc)
933 keyword_item counterTags[] = {
935 { "labelstring", CT_LABELSTRING },
936 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
938 { "within", CT_WITHIN }
941 lexrc.pushTable(counterTags, CT_END);
945 docstring labelstring;
946 docstring labelstring_appendix;
949 while (!getout && lexrc.isOK()) {
950 int le = lexrc.lex();
952 case Lexer::LEX_UNDEF:
953 lexrc.printError("Unknown counter tag `$$Token'");
957 switch (static_cast<CounterTags>(le)) {
960 name = lexrc.getDocString();
961 if (counters_->hasCounter(name))
962 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
964 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
968 within = lexrc.getDocString();
969 if (within == "none")
974 labelstring = lexrc.getDocString();
975 labelstring_appendix = labelstring;
977 case CT_LABELSTRING_APPENDIX:
979 labelstring_appendix = lexrc.getDocString();
987 // Here if have a full counter if getout == true
989 counters_->newCounter(name, within,
990 labelstring, labelstring_appendix);
996 FontInfo const & TextClass::defaultfont() const
1002 docstring const & TextClass::leftmargin() const
1008 docstring const & TextClass::rightmargin() const
1010 return rightmargin_;
1014 bool TextClass::hasLayout(docstring const & n) const
1016 docstring const name = n.empty() ? defaultLayoutName() : n;
1018 return find_if(layoutlist_.begin(), layoutlist_.end(),
1019 LayoutNamesEqual(name))
1020 != layoutlist_.end();
1025 LayoutPtr const & TextClass::operator[](docstring const & name) const
1027 BOOST_ASSERT(!name.empty());
1029 LayoutList::const_iterator cit =
1030 find_if(layoutlist_.begin(),
1032 LayoutNamesEqual(name));
1034 if (cit == layoutlist_.end()) {
1035 lyxerr << "We failed to find the layout '" << to_utf8(name)
1036 << "' in the layout list. You MUST investigate!"
1038 for (LayoutList::const_iterator it = layoutlist_.begin();
1039 it != layoutlist_.end(); ++it)
1040 lyxerr << " " << to_utf8(it->get()->name()) << endl;
1042 // we require the name to exist
1043 BOOST_ASSERT(false);
1050 bool TextClass::deleteLayout(docstring const & name)
1052 if (name == defaultLayoutName())
1055 LayoutList::iterator it =
1056 remove_if(layoutlist_.begin(), layoutlist_.end(),
1057 LayoutNamesEqual(name));
1059 LayoutList::iterator end = layoutlist_.end();
1060 bool const ret = (it != end);
1061 layoutlist_.erase(it, end);
1066 // Load textclass info if not loaded yet
1067 bool TextClass::load(string const & path) const
1072 // Read style-file, provided path is searched before the system ones
1073 FileName layout_file;
1075 layout_file = FileName(addName(path, name_ + ".layout"));
1076 if (layout_file.empty() || !layout_file.exists())
1077 layout_file = libFileSearch("layouts", name_, "layout");
1078 loaded_ = const_cast<TextClass*>(this)->read(layout_file) == 0;
1081 lyxerr << "Error reading `"
1082 << to_utf8(makeDisplayPath(layout_file.absFilename()))
1083 << "'\n(Check `" << name_
1084 << "')\nCheck your installation and "
1085 "try Options/Reconfigure..." << endl;
1092 FloatList & TextClass::floats()
1094 return *floatlist_.get();
1098 FloatList const & TextClass::floats() const
1100 return *floatlist_.get();
1104 Counters & TextClass::counters() const
1106 return *counters_.get();
1110 // Return the layout object of an inset given by name. If the name
1111 // is not found as such, the part after the ':' is stripped off, and
1112 // searched again. In this way, an error fallback can be provided:
1113 // An erroneous 'CharStyle:badname' (e.g., after a documentclass switch)
1114 // will invoke the layout object defined by name = 'CharStyle'.
1115 // If that doesn't work either, an empty object returns (shouldn't
1116 // happen). -- Idea JMarc, comment MV
1117 InsetLayout const & TextClass::insetlayout(docstring const & name) const
1120 while (!n.empty()) {
1121 if (insetlayoutlist_.count(n) > 0)
1122 return insetlayoutlist_[n];
1123 docstring::size_type i = n.find(':');
1124 if (i == string::npos)
1128 static InsetLayout empty;
1129 empty.labelstring = from_utf8("UNDEFINED");
1130 empty.labelfont = sane_font;
1131 empty.labelfont.setColor(Color_error);
1132 empty.bgcolor = Color_error;
1137 docstring const & TextClass::defaultLayoutName() const
1139 // This really should come from the actual layout... (Lgb)
1140 return defaultlayout_;
1144 LayoutPtr const & TextClass::defaultLayout() const
1146 return operator[](defaultLayoutName());
1150 string const & TextClass::name() const
1156 string const & TextClass::latexname() const
1158 const_cast<TextClass*>(this)->load();
1163 string const & TextClass::description() const
1165 return description_;
1169 string const & TextClass::opt_fontsize() const
1171 return opt_fontsize_;
1175 string const & TextClass::opt_pagestyle() const
1177 return opt_pagestyle_;
1181 string const & TextClass::options() const
1187 string const & TextClass::class_header() const
1189 return class_header_;
1193 string const & TextClass::pagestyle() const
1199 docstring const & TextClass::preamble() const
1205 PageSides TextClass::sides() const
1211 int TextClass::secnumdepth() const
1213 return secnumdepth_;
1217 int TextClass::tocdepth() const
1223 OutputType TextClass::outputType() const
1229 bool TextClass::provides(string const & p) const
1231 return provides_.find(p) != provides_.end();
1235 unsigned int TextClass::columns() const
1241 TitleLatexType TextClass::titletype() const
1247 string const & TextClass::titlename() const
1253 int TextClass::size() const
1255 return layoutlist_.size();
1259 int TextClass::min_toclevel() const
1261 return min_toclevel_;
1265 int TextClass::max_toclevel() const
1267 return max_toclevel_;
1271 bool TextClass::hasTocLevels() const
1273 return min_toclevel_ != Layout::NOT_IN_TOC;
1277 ostream & operator<<(ostream & os, PageSides p)