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"
42 #include "boost/assert.hpp"
45 using namespace lyx::support;
51 class LayoutNamesEqual : public unary_function<Layout, bool> {
53 LayoutNamesEqual(docstring const & name)
56 bool operator()(Layout const & c) const
58 return c.name() == name_;
68 bool layout2layout(FileName const & filename, FileName const & tempfile)
70 FileName const script = libFileSearch("scripts", "layout2layout.py");
72 LYXERR0("Could not find layout conversion "
73 "script layout2layout.py.");
77 ostringstream command;
78 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
79 << ' ' << quoteName(filename.toFilesystemEncoding())
80 << ' ' << quoteName(tempfile.toFilesystemEncoding());
81 string const command_str = command.str();
83 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
85 cmd_ret const ret = runCommand(command_str);
87 LYXERR0("Could not run layout conversion script layout2layout.py.");
94 std::string translateRT(TextClass::ReadType rt)
97 case TextClass::BASECLASS:
99 case TextClass::MERGE:
101 case TextClass::MODULE:
102 return "module file";
103 case TextClass::VALIDATION:
113 docstring const TextClass::emptylayout_ = from_ascii(N_("Plain Layout"));
116 InsetLayout DocumentClass::empty_insetlayout_;
119 TextClass::TextClass()
126 pagestyle_ = "default";
127 defaultfont_ = sane_font;
128 opt_fontsize_ = "10|11|12";
129 opt_pagestyle_ = "empty|plain|headings|fancy";
130 titletype_ = TITLE_COMMAND_AFTER;
131 titlename_ = "maketitle";
136 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
138 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
139 if (!lay.read(lexrc, *this)) {
140 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
144 lay.resfont = lay.font;
145 lay.resfont.realize(defaultfont_);
146 lay.reslabelfont = lay.labelfont;
147 lay.reslabelfont.realize(defaultfont_);
148 return true; // no errors
184 LexerKeyword textClassTags[] = {
185 { "addtopreamble", TC_ADDTOPREAMBLE },
186 { "classoptions", TC_CLASSOPTIONS },
187 { "columns", TC_COLUMNS },
188 { "counter", TC_COUNTER },
189 { "defaultfont", TC_DEFAULTFONT },
190 { "defaultstyle", TC_DEFAULTSTYLE },
191 { "environment", TC_ENVIRONMENT },
192 { "float", TC_FLOAT },
193 { "format", TC_FORMAT },
194 { "input", TC_INPUT },
195 { "insetlayout", TC_INSETLAYOUT },
196 { "leftmargin", TC_LEFTMARGIN },
197 { "nofloat", TC_NOFLOAT },
198 { "nostyle", TC_NOSTYLE },
199 { "outputtype", TC_OUTPUTTYPE },
200 { "pagestyle", TC_PAGESTYLE },
201 { "preamble", TC_PREAMBLE },
202 { "provides", TC_PROVIDES },
203 { "requires", TC_REQUIRES },
204 { "rightmargin", TC_RIGHTMARGIN },
205 { "secnumdepth", TC_SECNUMDEPTH },
206 { "sides", TC_SIDES },
207 { "style", TC_STYLE },
208 { "titlelatexname", TC_TITLELATEXNAME },
209 { "titlelatextype", TC_TITLELATEXTYPE },
210 { "tocdepth", TC_TOCDEPTH }
216 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
218 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
219 FileName const tempfile = FileName::tempName();
220 bool success = layout2layout(filename, tempfile);
222 success = read(tempfile, rt);
223 tempfile.removeFile();
227 bool TextClass::read(FileName const & filename, ReadType rt)
229 if (!filename.isReadableFile()) {
230 lyxerr << "Cannot read layout file `" << filename << "'."
235 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
236 to_utf8(makeDisplayPath(filename.absFilename())));
238 // Define the `empty' layout used in table cells, ert, etc. Note that
239 // we do this before loading any layout file, so that classes can
240 // override features of this layout if they should choose to do so.
241 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
242 static char const * s = "Margin Static\n"
243 "LatexType Paragraph\n"
246 "AlignPossible Left, Right, Center\n"
247 "LabelType No_Label\n"
250 Lexer lex(textClassTags);
253 lay.setName(emptylayout_);
254 if (!readStyle(lex, lay)) {
255 // The only way this happens is because the hardcoded layout above
259 layoutlist_.push_back(lay);
262 Lexer lexrc(textClassTags);
263 lexrc.setFile(filename);
264 ReturnValues retval = read(lexrc, rt);
266 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
267 to_utf8(makeDisplayPath(filename.absFilename())));
269 if (retval != FORMAT_MISMATCH)
272 bool const worx = convertLayoutFormat(filename, rt);
274 lyxerr << "Unable to convert " << filename <<
275 " to format " << FORMAT << std::endl;
282 bool TextClass::validate(std::string const & str)
285 return tc.read(str, VALIDATION);
289 bool TextClass::read(std::string const & str, ReadType rt)
291 Lexer lexrc(textClassTags);
292 istringstream is(str);
294 ReturnValues retval = read(lexrc, rt);
296 if (retval != FORMAT_MISMATCH)
299 // write the layout string to a temporary file
300 FileName const tempfile = FileName::tempName();
301 ofstream os(tempfile.toFilesystemEncoding().c_str());
303 LYXERR0("Unable to create tempoary file");
309 // now try to convert it
310 bool const worx = convertLayoutFormat(tempfile, rt);
312 LYXERR0("Unable to convert internal layout information to format "
315 tempfile.removeFile();
320 // Reads a textclass structure from file.
321 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
323 bool error = !lexrc.isOK();
325 // Format of files before the 'Format' tag was introduced
329 while (lexrc.isOK() && !error) {
330 int le = lexrc.lex();
333 case Lexer::LEX_FEOF:
336 case Lexer::LEX_UNDEF:
337 lexrc.printError("Unknown TextClass tag `$$Token'");
345 switch (static_cast<TextClassTags>(le)) {
349 format = lexrc.getInteger();
352 case TC_OUTPUTTYPE: // output type definition
353 readOutputType(lexrc);
356 case TC_INPUT: // Include file
358 string const inc = lexrc.getString();
359 FileName tmp = libFileSearch("layouts", inc,
363 lexrc.printError("Could not find input file: " + inc);
365 } else if (!read(tmp, MERGE)) {
366 lexrc.printError("Error reading input"
367 "file: " + tmp.absFilename());
373 case TC_DEFAULTSTYLE:
375 docstring const name = from_utf8(subst(lexrc.getString(),
377 defaultlayout_ = name;
384 docstring const name = from_utf8(subst(lexrc.getString(),
387 string s = "Could not read name for style: `$$Token' "
388 + lexrc.getString() + " is probably not valid UTF-8!";
389 lexrc.printError(s.c_str());
391 // Since we couldn't read the name, we just scan the rest
392 // of the style and discard it.
393 error = !readStyle(lexrc, lay);
394 } else if (hasLayout(name)) {
395 Layout & lay = operator[](name);
396 error = !readStyle(lexrc, lay);
399 layout.setName(name);
400 if (le == TC_ENVIRONMENT)
401 layout.is_environment = true;
402 error = !readStyle(lexrc, layout);
404 layoutlist_.push_back(layout);
406 if (defaultlayout_.empty()) {
407 // We do not have a default layout yet, so we choose
408 // the first layout we encounter.
409 defaultlayout_ = name;
414 //FIXME Should we also eat the style here? viz:
416 //readStyle(lexrc, layout);
418 lexrc.printError("No name given for style: `$$Token'.");
425 docstring const style = from_utf8(subst(lexrc.getString(),
427 if (!deleteLayout(style))
428 lyxerr << "Cannot delete style `"
429 << to_utf8(style) << '\'' << endl;
435 columns_ = lexrc.getInteger();
440 switch (lexrc.getInteger()) {
441 case 1: sides_ = OneSide; break;
442 case 2: sides_ = TwoSides; break;
444 lyxerr << "Impossible number of page"
445 " sides, setting to one."
455 pagestyle_ = rtrim(lexrc.getString());
459 defaultfont_ = lyxRead(lexrc);
460 if (!defaultfont_.resolved()) {
461 lexrc.printError("Warning: defaultfont should "
462 "be fully instantiated!");
463 defaultfont_.realize(sane_font);
469 secnumdepth_ = lexrc.getInteger();
474 tocdepth_ = lexrc.getInteger();
477 // First step to support options
478 case TC_CLASSOPTIONS:
479 readClassOptions(lexrc);
483 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
486 case TC_ADDTOPREAMBLE:
487 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
492 string const feature = lexrc.getString();
494 if (lexrc.getInteger())
495 provides_.insert(feature);
497 provides_.erase(feature);
503 vector<string> const req
504 = getVectorFromString(lexrc.getString());
505 requires_.insert(req.begin(), req.end());
509 case TC_LEFTMARGIN: // left margin type
511 leftmargin_ = lexrc.getDocString();
514 case TC_RIGHTMARGIN: // right margin type
516 rightmargin_ = lexrc.getDocString();
523 insetlayoutlist_[il.name()] = il;
524 // else there was an error, so forget it
536 case TC_TITLELATEXTYPE:
537 readTitleType(lexrc);
540 case TC_TITLELATEXNAME:
542 titlename_ = lexrc.getString();
547 string const nofloat = lexrc.getString();
548 floatlist_.erase(nofloat);
553 //Note that this is triggered the first time through the loop unless
554 //we hit a format tag.
555 if (format != FORMAT)
559 if (format != FORMAT)
560 return FORMAT_MISMATCH;
563 return (error ? ERROR : OK);
565 if (defaultlayout_.empty()) {
566 LYXERR0("Error: Textclass '" << name_
567 << "' is missing a defaultstyle.");
571 // Try to erase "stdinsets" from the provides_ set.
573 // Provides stdinsets 1
574 // declaration simply tells us that the standard insets have been
575 // defined. (It's found in stdinsets.inc but could also be used in
576 // user-defined files.) There isn't really any such package. So we
577 // might as well go ahead and erase it.
578 // If we do not succeed, then it was not there, which means that
579 // the textclass did not provide the definitions of the standard
580 // insets. So we need to try to load them.
581 int erased = provides_.erase("stdinsets");
583 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
586 throw ExceptionMessage(WarningException, _("Missing File"),
587 _("Could not find stdinsets.inc! This may lead to data loss!"));
589 } else if (!read(tmp, MERGE)) {
590 throw ExceptionMessage(WarningException, _("Corrupt File"),
591 _("Could not read stdinsets.inc! This may lead to data loss!"));
596 min_toclevel_ = Layout::NOT_IN_TOC;
597 max_toclevel_ = Layout::NOT_IN_TOC;
598 const_iterator lit = begin();
599 const_iterator len = end();
600 for (; lit != len; ++lit) {
601 int const toclevel = lit->toclevel;
602 if (toclevel != Layout::NOT_IN_TOC) {
603 if (min_toclevel_ == Layout::NOT_IN_TOC)
604 min_toclevel_ = toclevel;
606 min_toclevel_ = min(min_toclevel_, toclevel);
607 max_toclevel_ = max(max_toclevel_, toclevel);
610 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
611 << ", maximum is " << max_toclevel_);
613 return (error ? ERROR : OK);
617 void TextClass::readTitleType(Lexer & lexrc)
619 LexerKeyword titleTypeTags[] = {
620 { "commandafter", TITLE_COMMAND_AFTER },
621 { "environment", TITLE_ENVIRONMENT }
624 PushPopHelper pph(lexrc, titleTypeTags);
626 int le = lexrc.lex();
628 case Lexer::LEX_UNDEF:
629 lexrc.printError("Unknown output type `$$Token'");
631 case TITLE_COMMAND_AFTER:
632 case TITLE_ENVIRONMENT:
633 titletype_ = static_cast<TitleLatexType>(le);
636 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
642 void TextClass::readOutputType(Lexer & lexrc)
644 LexerKeyword outputTypeTags[] = {
645 { "docbook", DOCBOOK },
647 { "literate", LITERATE }
650 PushPopHelper pph(lexrc, outputTypeTags);
652 int le = lexrc.lex();
654 case Lexer::LEX_UNDEF:
655 lexrc.printError("Unknown output type `$$Token'");
660 outputType_ = static_cast<OutputType>(le);
663 LYXERR0("Unhandled value " << le);
669 void TextClass::readClassOptions(Lexer & lexrc)
679 LexerKeyword classOptionsTags[] = {
681 {"fontsize", CO_FONTSIZE },
682 {"header", CO_HEADER },
683 {"other", CO_OTHER },
684 {"pagestyle", CO_PAGESTYLE }
687 lexrc.pushTable(classOptionsTags);
689 while (!getout && lexrc.isOK()) {
690 int le = lexrc.lex();
692 case Lexer::LEX_UNDEF:
693 lexrc.printError("Unknown ClassOption tag `$$Token'");
700 opt_fontsize_ = rtrim(lexrc.getString());
704 opt_pagestyle_ = rtrim(lexrc.getString());
708 options_ = lexrc.getString();
712 class_header_ = subst(lexrc.getString(), """, "\"");
723 void TextClass::readFloat(Lexer & lexrc)
737 LexerKeyword floatTags[] = {
739 { "extension", FT_EXT },
740 { "guiname", FT_NAME },
741 { "latexbuiltin", FT_BUILTIN },
742 { "listname", FT_LISTNAME },
743 { "numberwithin", FT_WITHIN },
744 { "placement", FT_PLACEMENT },
745 { "style", FT_STYLE },
749 lexrc.pushTable(floatTags);
758 bool builtin = false;
761 while (!getout && lexrc.isOK()) {
762 int le = lexrc.lex();
764 case Lexer::LEX_UNDEF:
765 lexrc.printError("Unknown float tag `$$Token'");
772 type = lexrc.getString();
773 if (floatlist_.typeExist(type)) {
774 Floating const & fl = floatlist_.getType(type);
775 placement = fl.placement();
777 within = fl.within();
780 listName = fl.listName();
781 builtin = fl.builtin();
786 name = lexrc.getString();
790 placement = lexrc.getString();
794 ext = lexrc.getString();
798 within = lexrc.getString();
799 if (within == "none")
804 style = lexrc.getString();
808 listName = lexrc.getString();
812 builtin = lexrc.getBool();
820 // Here if have a full float if getout == true
822 Floating fl(type, placement, ext, within,
823 style, name, listName, builtin);
824 floatlist_.newFloat(fl);
825 // each float has its own counter
826 counters_.newCounter(from_ascii(type), from_ascii(within),
827 docstring(), docstring());
828 // also define sub-float counters
829 docstring const subtype = "sub-" + from_ascii(type);
830 counters_.newCounter(subtype, from_ascii(type),
831 "\\alph{" + subtype + "}", docstring());
838 void TextClass::readCounter(Lexer & lexrc)
844 CT_LABELSTRING_APPENDIX,
848 LexerKeyword counterTags[] = {
850 { "labelstring", CT_LABELSTRING },
851 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
853 { "within", CT_WITHIN }
856 lexrc.pushTable(counterTags);
860 docstring labelstring;
861 docstring labelstring_appendix;
864 while (!getout && lexrc.isOK()) {
865 int le = lexrc.lex();
867 case Lexer::LEX_UNDEF:
868 lexrc.printError("Unknown counter tag `$$Token'");
875 name = lexrc.getDocString();
876 if (counters_.hasCounter(name))
877 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
879 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
883 within = lexrc.getDocString();
884 if (within == "none")
889 labelstring = lexrc.getDocString();
890 labelstring_appendix = labelstring;
892 case CT_LABELSTRING_APPENDIX:
894 labelstring_appendix = lexrc.getDocString();
902 // Here if have a full counter if getout == true
904 counters_.newCounter(name, within,
905 labelstring, labelstring_appendix);
911 bool TextClass::hasLayout(docstring const & n) const
913 docstring const name = n.empty() ? defaultLayoutName() : n;
915 return find_if(layoutlist_.begin(), layoutlist_.end(),
916 LayoutNamesEqual(name))
917 != layoutlist_.end();
922 Layout const & TextClass::operator[](docstring const & name) const
924 BOOST_ASSERT(!name.empty());
927 find_if(begin(), end(), LayoutNamesEqual(name));
930 lyxerr << "We failed to find the layout '" << to_utf8(name)
931 << "' in the layout list. You MUST investigate!"
933 for (const_iterator cit = begin(); cit != end(); ++cit)
934 lyxerr << " " << to_utf8(cit->name()) << endl;
936 // we require the name to exist
944 Layout & TextClass::operator[](docstring const & name)
946 BOOST_ASSERT(!name.empty());
948 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
951 LYXERR0("We failed to find the layout '" << to_utf8(name)
952 << "' in the layout list. You MUST investigate!");
953 for (const_iterator cit = begin(); cit != end(); ++cit)
954 LYXERR0(" " << to_utf8(cit->name()));
956 // we require the name to exist
964 bool TextClass::deleteLayout(docstring const & name)
966 if (name == defaultLayoutName() || name == emptyLayoutName())
969 LayoutList::iterator it =
970 remove_if(layoutlist_.begin(), layoutlist_.end(),
971 LayoutNamesEqual(name));
973 LayoutList::iterator end = layoutlist_.end();
974 bool const ret = (it != end);
975 layoutlist_.erase(it, end);
980 // Load textclass info if not loaded yet
981 bool TextClass::load(string const & path) const
986 // Read style-file, provided path is searched before the system ones
987 FileName layout_file;
989 layout_file = FileName(addName(path, name_ + ".layout"));
990 if (layout_file.empty() || !layout_file.exists())
991 layout_file = libFileSearch("layouts", name_, "layout");
992 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
995 lyxerr << "Error reading `"
996 << to_utf8(makeDisplayPath(layout_file.absFilename()))
997 << "'\n(Check `" << name_
998 << "')\nCheck your installation and "
999 "try Options/Reconfigure..." << endl;
1006 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1009 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1010 while (!n.empty()) {
1011 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1012 if (cit != cen && cit->first == n)
1014 size_t i = n.find(':');
1015 if (i == string::npos)
1019 return empty_insetlayout_;
1023 docstring const & TextClass::defaultLayoutName() const
1025 // This really should come from the actual layout... (Lgb)
1026 return defaultlayout_;
1030 Layout const & TextClass::defaultLayout() const
1032 return operator[](defaultLayoutName());
1036 bool TextClass::isDefaultLayout(Layout const & lay) const
1038 return lay.name() == defaultLayoutName();
1042 bool TextClass::isEmptyLayout(Layout const & lay) const
1044 return lay.name() == emptyLayoutName();
1048 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1050 DocumentClass * dc = new DocumentClass(baseClass);
1051 tc_list_.push_back(dc);
1052 return *tc_list_.back();
1056 DocumentClassBundle & DocumentClassBundle::get()
1058 static DocumentClassBundle singleton;
1063 DocumentClass::DocumentClass(LayoutFile const & tc)
1068 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1070 LayoutList::const_iterator it = layoutlist_.begin();
1071 LayoutList::const_iterator end = layoutlist_.end();
1072 for (; it != end; ++it)
1073 if (it->latexname() == lay)
1079 bool DocumentClass::provides(string const & p) const
1081 return provides_.find(p) != provides_.end();
1085 bool DocumentClass::hasTocLevels() const
1087 return min_toclevel_ != Layout::NOT_IN_TOC;
1091 ostream & operator<<(ostream & os, PageSides p)