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/assert.h"
31 #include "support/debug.h"
32 #include "support/ExceptionMessage.h"
33 #include "support/FileName.h"
34 #include "support/filetools.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/os.h"
44 using namespace lyx::support;
50 class LayoutNamesEqual : public unary_function<Layout, bool> {
52 LayoutNamesEqual(docstring const & name)
55 bool operator()(Layout const & c) const
57 return c.name() == name_;
67 bool layout2layout(FileName const & filename, FileName const & tempfile)
69 FileName const script = libFileSearch("scripts", "layout2layout.py");
71 LYXERR0("Could not find layout conversion "
72 "script layout2layout.py.");
76 ostringstream command;
77 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
78 << ' ' << quoteName(filename.toFilesystemEncoding())
79 << ' ' << quoteName(tempfile.toFilesystemEncoding());
80 string const command_str = command.str();
82 LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
84 cmd_ret const ret = runCommand(command_str);
86 LYXERR0("Could not run layout conversion script layout2layout.py.");
93 std::string translateRT(TextClass::ReadType rt)
96 case TextClass::BASECLASS:
98 case TextClass::MERGE:
100 case TextClass::MODULE:
101 return "module file";
102 case TextClass::VALIDATION:
112 docstring const TextClass::emptylayout_ = from_ascii(N_("Plain Layout"));
115 InsetLayout DocumentClass::empty_insetlayout_;
118 TextClass::TextClass()
125 pagestyle_ = "default";
126 defaultfont_ = sane_font;
127 opt_fontsize_ = "10|11|12";
128 opt_pagestyle_ = "empty|plain|headings|fancy";
129 titletype_ = TITLE_COMMAND_AFTER;
130 titlename_ = "maketitle";
135 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
137 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
138 if (!lay.read(lexrc, *this)) {
139 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
143 lay.resfont = lay.font;
144 lay.resfont.realize(defaultfont_);
145 lay.reslabelfont = lay.labelfont;
146 lay.reslabelfont.realize(defaultfont_);
147 return true; // no errors
183 LexerKeyword textClassTags[] = {
184 { "addtopreamble", TC_ADDTOPREAMBLE },
185 { "classoptions", TC_CLASSOPTIONS },
186 { "columns", TC_COLUMNS },
187 { "counter", TC_COUNTER },
188 { "defaultfont", TC_DEFAULTFONT },
189 { "defaultstyle", TC_DEFAULTSTYLE },
190 { "environment", TC_ENVIRONMENT },
191 { "float", TC_FLOAT },
192 { "format", TC_FORMAT },
193 { "input", TC_INPUT },
194 { "insetlayout", TC_INSETLAYOUT },
195 { "leftmargin", TC_LEFTMARGIN },
196 { "nofloat", TC_NOFLOAT },
197 { "nostyle", TC_NOSTYLE },
198 { "outputtype", TC_OUTPUTTYPE },
199 { "pagestyle", TC_PAGESTYLE },
200 { "preamble", TC_PREAMBLE },
201 { "provides", TC_PROVIDES },
202 { "requires", TC_REQUIRES },
203 { "rightmargin", TC_RIGHTMARGIN },
204 { "secnumdepth", TC_SECNUMDEPTH },
205 { "sides", TC_SIDES },
206 { "style", TC_STYLE },
207 { "titlelatexname", TC_TITLELATEXNAME },
208 { "titlelatextype", TC_TITLELATEXTYPE },
209 { "tocdepth", TC_TOCDEPTH }
215 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
217 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
218 FileName const tempfile = FileName::tempName();
219 bool success = layout2layout(filename, tempfile);
221 success = read(tempfile, rt);
222 tempfile.removeFile();
226 bool TextClass::read(FileName const & filename, ReadType rt)
228 if (!filename.isReadableFile()) {
229 lyxerr << "Cannot read layout file `" << filename << "'."
234 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
235 to_utf8(makeDisplayPath(filename.absFilename())));
237 // Define the `empty' layout used in table cells, ert, etc. Note that
238 // we do this before loading any layout file, so that classes can
239 // override features of this layout if they should choose to do so.
240 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
241 static char const * s = "Margin Static\n"
242 "LatexType Paragraph\n"
245 "AlignPossible Left, Right, Center\n"
246 "LabelType No_Label\n"
249 Lexer lex(textClassTags);
252 lay.setName(emptylayout_);
253 if (!readStyle(lex, lay)) {
254 // The only way this happens is because the hardcoded layout above
256 LASSERT(false, /**/);
258 layoutlist_.push_back(lay);
261 Lexer lexrc(textClassTags);
262 lexrc.setFile(filename);
263 ReturnValues retval = read(lexrc, rt);
265 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
266 to_utf8(makeDisplayPath(filename.absFilename())));
268 if (retval != FORMAT_MISMATCH)
271 bool const worx = convertLayoutFormat(filename, rt);
273 lyxerr << "Unable to convert " << filename <<
274 " to format " << FORMAT << std::endl;
281 bool TextClass::validate(std::string const & str)
284 return tc.read(str, VALIDATION);
288 bool TextClass::read(std::string const & str, ReadType rt)
290 Lexer lexrc(textClassTags);
291 istringstream is(str);
293 ReturnValues retval = read(lexrc, rt);
295 if (retval != FORMAT_MISMATCH)
298 // write the layout string to a temporary file
299 FileName const tempfile = FileName::tempName();
300 ofstream os(tempfile.toFilesystemEncoding().c_str());
302 LYXERR0("Unable to create tempoary file");
308 // now try to convert it
309 bool const worx = convertLayoutFormat(tempfile, rt);
311 LYXERR0("Unable to convert internal layout information to format "
314 tempfile.removeFile();
319 // Reads a textclass structure from file.
320 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
322 bool error = !lexrc.isOK();
324 // Format of files before the 'Format' tag was introduced
328 while (lexrc.isOK() && !error) {
329 int le = lexrc.lex();
332 case Lexer::LEX_FEOF:
335 case Lexer::LEX_UNDEF:
336 lexrc.printError("Unknown TextClass tag `$$Token'");
344 switch (static_cast<TextClassTags>(le)) {
348 format = lexrc.getInteger();
351 case TC_OUTPUTTYPE: // output type definition
352 readOutputType(lexrc);
355 case TC_INPUT: // Include file
357 string const inc = lexrc.getString();
358 FileName tmp = libFileSearch("layouts", inc,
362 lexrc.printError("Could not find input file: " + inc);
364 } else if (!read(tmp, MERGE)) {
365 lexrc.printError("Error reading input"
366 "file: " + tmp.absFilename());
372 case TC_DEFAULTSTYLE:
374 docstring const name = from_utf8(subst(lexrc.getString(),
376 defaultlayout_ = name;
383 docstring const name = from_utf8(subst(lexrc.getString(),
386 string s = "Could not read name for style: `$$Token' "
387 + lexrc.getString() + " is probably not valid UTF-8!";
388 lexrc.printError(s.c_str());
390 // Since we couldn't read the name, we just scan the rest
391 // of the style and discard it.
392 error = !readStyle(lexrc, lay);
393 } else if (hasLayout(name)) {
394 Layout & lay = operator[](name);
395 error = !readStyle(lexrc, lay);
398 layout.setName(name);
399 if (le == TC_ENVIRONMENT)
400 layout.is_environment = true;
401 error = !readStyle(lexrc, layout);
403 layoutlist_.push_back(layout);
405 if (defaultlayout_.empty()) {
406 // We do not have a default layout yet, so we choose
407 // the first layout we encounter.
408 defaultlayout_ = name;
413 //FIXME Should we also eat the style here? viz:
415 //readStyle(lexrc, layout);
417 lexrc.printError("No name given for style: `$$Token'.");
424 docstring const style = from_utf8(subst(lexrc.getString(),
426 if (!deleteLayout(style))
427 lyxerr << "Cannot delete style `"
428 << to_utf8(style) << '\'' << endl;
434 columns_ = lexrc.getInteger();
439 switch (lexrc.getInteger()) {
440 case 1: sides_ = OneSide; break;
441 case 2: sides_ = TwoSides; break;
443 lyxerr << "Impossible number of page"
444 " sides, setting to one."
454 pagestyle_ = rtrim(lexrc.getString());
458 defaultfont_ = lyxRead(lexrc);
459 if (!defaultfont_.resolved()) {
460 lexrc.printError("Warning: defaultfont should "
461 "be fully instantiated!");
462 defaultfont_.realize(sane_font);
468 secnumdepth_ = lexrc.getInteger();
473 tocdepth_ = lexrc.getInteger();
476 // First step to support options
477 case TC_CLASSOPTIONS:
478 readClassOptions(lexrc);
482 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
485 case TC_ADDTOPREAMBLE:
486 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
491 string const feature = lexrc.getString();
493 if (lexrc.getInteger())
494 provides_.insert(feature);
496 provides_.erase(feature);
502 vector<string> const req
503 = getVectorFromString(lexrc.getString());
504 requires_.insert(req.begin(), req.end());
508 case TC_LEFTMARGIN: // left margin type
510 leftmargin_ = lexrc.getDocString();
513 case TC_RIGHTMARGIN: // right margin type
515 rightmargin_ = lexrc.getDocString();
522 insetlayoutlist_[il.name()] = il;
523 // else there was an error, so forget it
535 case TC_TITLELATEXTYPE:
536 readTitleType(lexrc);
539 case TC_TITLELATEXNAME:
541 titlename_ = lexrc.getString();
546 string const nofloat = lexrc.getString();
547 floatlist_.erase(nofloat);
552 //Note that this is triggered the first time through the loop unless
553 //we hit a format tag.
554 if (format != FORMAT)
558 if (format != FORMAT)
559 return FORMAT_MISMATCH;
562 return (error ? ERROR : OK);
564 if (defaultlayout_.empty()) {
565 LYXERR0("Error: Textclass '" << name_
566 << "' is missing a defaultstyle.");
570 // Try to erase "stdinsets" from the provides_ set.
572 // Provides stdinsets 1
573 // declaration simply tells us that the standard insets have been
574 // defined. (It's found in stdinsets.inc but could also be used in
575 // user-defined files.) There isn't really any such package. So we
576 // might as well go ahead and erase it.
577 // If we do not succeed, then it was not there, which means that
578 // the textclass did not provide the definitions of the standard
579 // insets. So we need to try to load them.
580 int erased = provides_.erase("stdinsets");
582 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
585 throw ExceptionMessage(WarningException, _("Missing File"),
586 _("Could not find stdinsets.inc! This may lead to data loss!"));
588 } else if (!read(tmp, MERGE)) {
589 throw ExceptionMessage(WarningException, _("Corrupt File"),
590 _("Could not read stdinsets.inc! This may lead to data loss!"));
595 min_toclevel_ = Layout::NOT_IN_TOC;
596 max_toclevel_ = Layout::NOT_IN_TOC;
597 const_iterator lit = begin();
598 const_iterator len = end();
599 for (; lit != len; ++lit) {
600 int const toclevel = lit->toclevel;
601 if (toclevel != Layout::NOT_IN_TOC) {
602 if (min_toclevel_ == Layout::NOT_IN_TOC)
603 min_toclevel_ = toclevel;
605 min_toclevel_ = min(min_toclevel_, toclevel);
606 max_toclevel_ = max(max_toclevel_, toclevel);
609 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
610 << ", maximum is " << max_toclevel_);
612 return (error ? ERROR : OK);
616 void TextClass::readTitleType(Lexer & lexrc)
618 LexerKeyword titleTypeTags[] = {
619 { "commandafter", TITLE_COMMAND_AFTER },
620 { "environment", TITLE_ENVIRONMENT }
623 PushPopHelper pph(lexrc, titleTypeTags);
625 int le = lexrc.lex();
627 case Lexer::LEX_UNDEF:
628 lexrc.printError("Unknown output type `$$Token'");
630 case TITLE_COMMAND_AFTER:
631 case TITLE_ENVIRONMENT:
632 titletype_ = static_cast<TitleLatexType>(le);
635 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
641 void TextClass::readOutputType(Lexer & lexrc)
643 LexerKeyword outputTypeTags[] = {
644 { "docbook", DOCBOOK },
646 { "literate", LITERATE }
649 PushPopHelper pph(lexrc, outputTypeTags);
651 int le = lexrc.lex();
653 case Lexer::LEX_UNDEF:
654 lexrc.printError("Unknown output type `$$Token'");
659 outputType_ = static_cast<OutputType>(le);
662 LYXERR0("Unhandled value " << le);
668 void TextClass::readClassOptions(Lexer & lexrc)
678 LexerKeyword classOptionsTags[] = {
680 {"fontsize", CO_FONTSIZE },
681 {"header", CO_HEADER },
682 {"other", CO_OTHER },
683 {"pagestyle", CO_PAGESTYLE }
686 lexrc.pushTable(classOptionsTags);
688 while (!getout && lexrc.isOK()) {
689 int le = lexrc.lex();
691 case Lexer::LEX_UNDEF:
692 lexrc.printError("Unknown ClassOption tag `$$Token'");
699 opt_fontsize_ = rtrim(lexrc.getString());
703 opt_pagestyle_ = rtrim(lexrc.getString());
707 options_ = lexrc.getString();
711 class_header_ = subst(lexrc.getString(), """, "\"");
722 void TextClass::readFloat(Lexer & lexrc)
736 LexerKeyword floatTags[] = {
738 { "extension", FT_EXT },
739 { "guiname", FT_NAME },
740 { "latexbuiltin", FT_BUILTIN },
741 { "listname", FT_LISTNAME },
742 { "numberwithin", FT_WITHIN },
743 { "placement", FT_PLACEMENT },
744 { "style", FT_STYLE },
748 lexrc.pushTable(floatTags);
757 bool builtin = false;
760 while (!getout && lexrc.isOK()) {
761 int le = lexrc.lex();
763 case Lexer::LEX_UNDEF:
764 lexrc.printError("Unknown float tag `$$Token'");
771 type = lexrc.getString();
772 if (floatlist_.typeExist(type)) {
773 Floating const & fl = floatlist_.getType(type);
774 placement = fl.placement();
776 within = fl.within();
779 listName = fl.listName();
780 builtin = fl.builtin();
785 name = lexrc.getString();
789 placement = lexrc.getString();
793 ext = lexrc.getString();
797 within = lexrc.getString();
798 if (within == "none")
803 style = lexrc.getString();
807 listName = lexrc.getString();
811 builtin = lexrc.getBool();
819 // Here if have a full float if getout == true
821 Floating fl(type, placement, ext, within,
822 style, name, listName, builtin);
823 floatlist_.newFloat(fl);
824 // each float has its own counter
825 counters_.newCounter(from_ascii(type), from_ascii(within),
826 docstring(), docstring());
827 // also define sub-float counters
828 docstring const subtype = "sub-" + from_ascii(type);
829 counters_.newCounter(subtype, from_ascii(type),
830 "\\alph{" + subtype + "}", docstring());
837 void TextClass::readCounter(Lexer & lexrc)
843 CT_LABELSTRING_APPENDIX,
847 LexerKeyword counterTags[] = {
849 { "labelstring", CT_LABELSTRING },
850 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
852 { "within", CT_WITHIN }
855 lexrc.pushTable(counterTags);
859 docstring labelstring;
860 docstring labelstring_appendix;
863 while (!getout && lexrc.isOK()) {
864 int le = lexrc.lex();
866 case Lexer::LEX_UNDEF:
867 lexrc.printError("Unknown counter tag `$$Token'");
874 name = lexrc.getDocString();
875 if (counters_.hasCounter(name))
876 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
878 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
882 within = lexrc.getDocString();
883 if (within == "none")
888 labelstring = lexrc.getDocString();
889 labelstring_appendix = labelstring;
891 case CT_LABELSTRING_APPENDIX:
893 labelstring_appendix = lexrc.getDocString();
901 // Here if have a full counter if getout == true
903 counters_.newCounter(name, within,
904 labelstring, labelstring_appendix);
910 bool TextClass::hasLayout(docstring const & n) const
912 docstring const name = n.empty() ? defaultLayoutName() : n;
914 return find_if(layoutlist_.begin(), layoutlist_.end(),
915 LayoutNamesEqual(name))
916 != layoutlist_.end();
921 Layout const & TextClass::operator[](docstring const & name) const
923 LASSERT(!name.empty(), /**/);
926 find_if(begin(), end(), LayoutNamesEqual(name));
929 lyxerr << "We failed to find the layout '" << to_utf8(name)
930 << "' in the layout list. You MUST investigate!"
932 for (const_iterator cit = begin(); cit != end(); ++cit)
933 lyxerr << " " << to_utf8(cit->name()) << endl;
935 // we require the name to exist
936 LASSERT(false, /**/);
943 Layout & TextClass::operator[](docstring const & name)
945 LASSERT(!name.empty(), /**/);
947 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
950 LYXERR0("We failed to find the layout '" << to_utf8(name)
951 << "' in the layout list. You MUST investigate!");
952 for (const_iterator cit = begin(); cit != end(); ++cit)
953 LYXERR0(" " << to_utf8(cit->name()));
955 // we require the name to exist
956 LASSERT(false, /**/);
963 bool TextClass::deleteLayout(docstring const & name)
965 if (name == defaultLayoutName() || name == emptyLayoutName())
968 LayoutList::iterator it =
969 remove_if(layoutlist_.begin(), layoutlist_.end(),
970 LayoutNamesEqual(name));
972 LayoutList::iterator end = layoutlist_.end();
973 bool const ret = (it != end);
974 layoutlist_.erase(it, end);
979 // Load textclass info if not loaded yet
980 bool TextClass::load(string const & path) const
985 // Read style-file, provided path is searched before the system ones
986 FileName layout_file;
988 layout_file = FileName(addName(path, name_ + ".layout"));
989 if (layout_file.empty() || !layout_file.exists())
990 layout_file = libFileSearch("layouts", name_, "layout");
991 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
994 lyxerr << "Error reading `"
995 << to_utf8(makeDisplayPath(layout_file.absFilename()))
996 << "'\n(Check `" << name_
997 << "')\nCheck your installation and "
998 "try Options/Reconfigure..." << endl;
1005 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1008 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1009 while (!n.empty()) {
1010 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1011 if (cit != cen && cit->first == n)
1013 size_t i = n.find(':');
1014 if (i == string::npos)
1018 return empty_insetlayout_;
1022 docstring const & TextClass::defaultLayoutName() const
1024 // This really should come from the actual layout... (Lgb)
1025 return defaultlayout_;
1029 Layout const & TextClass::defaultLayout() const
1031 return operator[](defaultLayoutName());
1035 bool TextClass::isDefaultLayout(Layout const & lay) const
1037 return lay.name() == defaultLayoutName();
1041 bool TextClass::isEmptyLayout(Layout const & lay) const
1043 return lay.name() == emptyLayoutName();
1047 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1049 DocumentClass * dc = new DocumentClass(baseClass);
1050 tc_list_.push_back(dc);
1051 return *tc_list_.back();
1055 DocumentClassBundle & DocumentClassBundle::get()
1057 static DocumentClassBundle singleton;
1062 DocumentClass::DocumentClass(LayoutFile const & tc)
1067 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1069 LayoutList::const_iterator it = layoutlist_.begin();
1070 LayoutList::const_iterator end = layoutlist_.end();
1071 for (; it != end; ++it)
1072 if (it->latexname() == lay)
1078 bool DocumentClass::provides(string const & p) const
1080 return provides_.find(p) != provides_.end();
1084 bool DocumentClass::hasTocLevels() const
1086 return min_toclevel_ != Layout::NOT_IN_TOC;
1090 ostream & operator<<(ostream & os, PageSides p)