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 // This string cannot be translated, because it is a layout identifier.
113 docstring const TextClass::emptylayout_ = from_ascii("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";
133 _("Plain Layout"); // a hack to make this translatable
137 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
139 LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
140 if (!lay.read(lexrc, *this)) {
141 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
145 lay.resfont = lay.font;
146 lay.resfont.realize(defaultfont_);
147 lay.reslabelfont = lay.labelfont;
148 lay.reslabelfont.realize(defaultfont_);
149 return true; // no errors
185 LexerKeyword textClassTags[] = {
186 { "addtopreamble", TC_ADDTOPREAMBLE },
187 { "classoptions", TC_CLASSOPTIONS },
188 { "columns", TC_COLUMNS },
189 { "counter", TC_COUNTER },
190 { "defaultfont", TC_DEFAULTFONT },
191 { "defaultstyle", TC_DEFAULTSTYLE },
192 { "environment", TC_ENVIRONMENT },
193 { "float", TC_FLOAT },
194 { "format", TC_FORMAT },
195 { "input", TC_INPUT },
196 { "insetlayout", TC_INSETLAYOUT },
197 { "leftmargin", TC_LEFTMARGIN },
198 { "nofloat", TC_NOFLOAT },
199 { "nostyle", TC_NOSTYLE },
200 { "outputtype", TC_OUTPUTTYPE },
201 { "pagestyle", TC_PAGESTYLE },
202 { "preamble", TC_PREAMBLE },
203 { "provides", TC_PROVIDES },
204 { "requires", TC_REQUIRES },
205 { "rightmargin", TC_RIGHTMARGIN },
206 { "secnumdepth", TC_SECNUMDEPTH },
207 { "sides", TC_SIDES },
208 { "style", TC_STYLE },
209 { "titlelatexname", TC_TITLELATEXNAME },
210 { "titlelatextype", TC_TITLELATEXTYPE },
211 { "tocdepth", TC_TOCDEPTH }
217 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
219 LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
220 FileName const tempfile = FileName::tempName();
221 bool success = layout2layout(filename, tempfile);
223 success = read(tempfile, rt);
224 tempfile.removeFile();
228 bool TextClass::read(FileName const & filename, ReadType rt)
230 if (!filename.isReadableFile()) {
231 lyxerr << "Cannot read layout file `" << filename << "'."
236 LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
237 to_utf8(makeDisplayPath(filename.absFilename())));
239 // Define the `empty' layout used in table cells, ert, etc. Note that
240 // we do this before loading any layout file, so that classes can
241 // override features of this layout if they should choose to do so.
242 if (rt == BASECLASS && !hasLayout(emptylayout_)) {
243 static char const * s = "Margin Static\n"
244 "LatexType Paragraph\n"
247 "AlignPossible Left, Right, Center\n"
248 "LabelType No_Label\n"
251 Lexer lex(textClassTags);
254 lay.setName(emptylayout_);
255 if (!readStyle(lex, lay)) {
256 // The only way this happens is because the hardcoded layout above
258 LASSERT(false, /**/);
260 layoutlist_.push_back(lay);
263 Lexer lexrc(textClassTags);
264 lexrc.setFile(filename);
265 ReturnValues retval = read(lexrc, rt);
267 LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
268 to_utf8(makeDisplayPath(filename.absFilename())));
270 if (retval != FORMAT_MISMATCH)
273 bool const worx = convertLayoutFormat(filename, rt);
275 lyxerr << "Unable to convert " << filename <<
276 " to format " << FORMAT << std::endl;
283 bool TextClass::validate(std::string const & str)
286 return tc.read(str, VALIDATION);
290 bool TextClass::read(std::string const & str, ReadType rt)
292 Lexer lexrc(textClassTags);
293 istringstream is(str);
295 ReturnValues retval = read(lexrc, rt);
297 if (retval != FORMAT_MISMATCH)
300 // write the layout string to a temporary file
301 FileName const tempfile = FileName::tempName();
302 ofstream os(tempfile.toFilesystemEncoding().c_str());
304 LYXERR0("Unable to create tempoary file");
310 // now try to convert it
311 bool const worx = convertLayoutFormat(tempfile, rt);
313 LYXERR0("Unable to convert internal layout information to format "
316 tempfile.removeFile();
321 // Reads a textclass structure from file.
322 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt)
324 bool error = !lexrc.isOK();
326 // Format of files before the 'Format' tag was introduced
330 while (lexrc.isOK() && !error) {
331 int le = lexrc.lex();
334 case Lexer::LEX_FEOF:
337 case Lexer::LEX_UNDEF:
338 lexrc.printError("Unknown TextClass tag `$$Token'");
346 switch (static_cast<TextClassTags>(le)) {
350 format = lexrc.getInteger();
353 case TC_OUTPUTTYPE: // output type definition
354 readOutputType(lexrc);
357 case TC_INPUT: // Include file
359 string const inc = lexrc.getString();
360 FileName tmp = libFileSearch("layouts", inc,
364 lexrc.printError("Could not find input file: " + inc);
366 } else if (!read(tmp, MERGE)) {
367 lexrc.printError("Error reading input"
368 "file: " + tmp.absFilename());
374 case TC_DEFAULTSTYLE:
376 docstring const name = from_utf8(subst(lexrc.getString(),
378 defaultlayout_ = name;
385 docstring const name = from_utf8(subst(lexrc.getString(),
388 string s = "Could not read name for style: `$$Token' "
389 + lexrc.getString() + " is probably not valid UTF-8!";
390 lexrc.printError(s.c_str());
392 // Since we couldn't read the name, we just scan the rest
393 // of the style and discard it.
394 error = !readStyle(lexrc, lay);
395 } else if (hasLayout(name)) {
396 Layout & lay = operator[](name);
397 error = !readStyle(lexrc, lay);
400 layout.setName(name);
401 if (le == TC_ENVIRONMENT)
402 layout.is_environment = true;
403 error = !readStyle(lexrc, layout);
405 layoutlist_.push_back(layout);
407 if (defaultlayout_.empty()) {
408 // We do not have a default layout yet, so we choose
409 // the first layout we encounter.
410 defaultlayout_ = name;
415 //FIXME Should we also eat the style here? viz:
417 //readStyle(lexrc, layout);
419 lexrc.printError("No name given for style: `$$Token'.");
426 docstring const style = from_utf8(subst(lexrc.getString(),
428 if (!deleteLayout(style))
429 lyxerr << "Cannot delete style `"
430 << to_utf8(style) << '\'' << endl;
436 columns_ = lexrc.getInteger();
441 switch (lexrc.getInteger()) {
442 case 1: sides_ = OneSide; break;
443 case 2: sides_ = TwoSides; break;
445 lyxerr << "Impossible number of page"
446 " sides, setting to one."
456 pagestyle_ = rtrim(lexrc.getString());
460 defaultfont_ = lyxRead(lexrc);
461 if (!defaultfont_.resolved()) {
462 lexrc.printError("Warning: defaultfont should "
463 "be fully instantiated!");
464 defaultfont_.realize(sane_font);
470 secnumdepth_ = lexrc.getInteger();
475 tocdepth_ = lexrc.getInteger();
478 // First step to support options
479 case TC_CLASSOPTIONS:
480 readClassOptions(lexrc);
484 preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
487 case TC_ADDTOPREAMBLE:
488 preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
493 string const feature = lexrc.getString();
495 if (lexrc.getInteger())
496 provides_.insert(feature);
498 provides_.erase(feature);
504 vector<string> const req
505 = getVectorFromString(lexrc.getString());
506 requires_.insert(req.begin(), req.end());
510 case TC_LEFTMARGIN: // left margin type
512 leftmargin_ = lexrc.getDocString();
515 case TC_RIGHTMARGIN: // right margin type
517 rightmargin_ = lexrc.getDocString();
524 insetlayoutlist_[il.name()] = il;
525 // else there was an error, so forget it
537 case TC_TITLELATEXTYPE:
538 readTitleType(lexrc);
541 case TC_TITLELATEXNAME:
543 titlename_ = lexrc.getString();
548 string const nofloat = lexrc.getString();
549 floatlist_.erase(nofloat);
554 //Note that this is triggered the first time through the loop unless
555 //we hit a format tag.
556 if (format != FORMAT)
560 if (format != FORMAT)
561 return FORMAT_MISMATCH;
564 return (error ? ERROR : OK);
566 if (defaultlayout_.empty()) {
567 LYXERR0("Error: Textclass '" << name_
568 << "' is missing a defaultstyle.");
572 // Try to erase "stdinsets" from the provides_ set.
574 // Provides stdinsets 1
575 // declaration simply tells us that the standard insets have been
576 // defined. (It's found in stdinsets.inc but could also be used in
577 // user-defined files.) There isn't really any such package. So we
578 // might as well go ahead and erase it.
579 // If we do not succeed, then it was not there, which means that
580 // the textclass did not provide the definitions of the standard
581 // insets. So we need to try to load them.
582 int erased = provides_.erase("stdinsets");
584 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
587 throw ExceptionMessage(WarningException, _("Missing File"),
588 _("Could not find stdinsets.inc! This may lead to data loss!"));
590 } else if (!read(tmp, MERGE)) {
591 throw ExceptionMessage(WarningException, _("Corrupt File"),
592 _("Could not read stdinsets.inc! This may lead to data loss!"));
597 min_toclevel_ = Layout::NOT_IN_TOC;
598 max_toclevel_ = Layout::NOT_IN_TOC;
599 const_iterator lit = begin();
600 const_iterator len = end();
601 for (; lit != len; ++lit) {
602 int const toclevel = lit->toclevel;
603 if (toclevel != Layout::NOT_IN_TOC) {
604 if (min_toclevel_ == Layout::NOT_IN_TOC)
605 min_toclevel_ = toclevel;
607 min_toclevel_ = min(min_toclevel_, toclevel);
608 max_toclevel_ = max(max_toclevel_, toclevel);
611 LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
612 << ", maximum is " << max_toclevel_);
614 return (error ? ERROR : OK);
618 void TextClass::readTitleType(Lexer & lexrc)
620 LexerKeyword titleTypeTags[] = {
621 { "commandafter", TITLE_COMMAND_AFTER },
622 { "environment", TITLE_ENVIRONMENT }
625 PushPopHelper pph(lexrc, titleTypeTags);
627 int le = lexrc.lex();
629 case Lexer::LEX_UNDEF:
630 lexrc.printError("Unknown output type `$$Token'");
632 case TITLE_COMMAND_AFTER:
633 case TITLE_ENVIRONMENT:
634 titletype_ = static_cast<TitleLatexType>(le);
637 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
643 void TextClass::readOutputType(Lexer & lexrc)
645 LexerKeyword outputTypeTags[] = {
646 { "docbook", DOCBOOK },
648 { "literate", LITERATE }
651 PushPopHelper pph(lexrc, outputTypeTags);
653 int le = lexrc.lex();
655 case Lexer::LEX_UNDEF:
656 lexrc.printError("Unknown output type `$$Token'");
661 outputType_ = static_cast<OutputType>(le);
664 LYXERR0("Unhandled value " << le);
670 void TextClass::readClassOptions(Lexer & lexrc)
680 LexerKeyword classOptionsTags[] = {
682 {"fontsize", CO_FONTSIZE },
683 {"header", CO_HEADER },
684 {"other", CO_OTHER },
685 {"pagestyle", CO_PAGESTYLE }
688 lexrc.pushTable(classOptionsTags);
690 while (!getout && lexrc.isOK()) {
691 int le = lexrc.lex();
693 case Lexer::LEX_UNDEF:
694 lexrc.printError("Unknown ClassOption tag `$$Token'");
701 opt_fontsize_ = rtrim(lexrc.getString());
705 opt_pagestyle_ = rtrim(lexrc.getString());
709 options_ = lexrc.getString();
713 class_header_ = subst(lexrc.getString(), """, "\"");
724 void TextClass::readFloat(Lexer & lexrc)
738 LexerKeyword floatTags[] = {
740 { "extension", FT_EXT },
741 { "guiname", FT_NAME },
742 { "latexbuiltin", FT_BUILTIN },
743 { "listname", FT_LISTNAME },
744 { "numberwithin", FT_WITHIN },
745 { "placement", FT_PLACEMENT },
746 { "style", FT_STYLE },
750 lexrc.pushTable(floatTags);
759 bool builtin = false;
762 while (!getout && lexrc.isOK()) {
763 int le = lexrc.lex();
765 case Lexer::LEX_UNDEF:
766 lexrc.printError("Unknown float tag `$$Token'");
773 type = lexrc.getString();
774 if (floatlist_.typeExist(type)) {
775 Floating const & fl = floatlist_.getType(type);
776 placement = fl.placement();
778 within = fl.within();
781 listName = fl.listName();
782 builtin = fl.builtin();
787 name = lexrc.getString();
791 placement = lexrc.getString();
795 ext = lexrc.getString();
799 within = lexrc.getString();
800 if (within == "none")
805 style = lexrc.getString();
809 listName = lexrc.getString();
813 builtin = lexrc.getBool();
821 // Here if have a full float if getout == true
823 Floating fl(type, placement, ext, within,
824 style, name, listName, builtin);
825 floatlist_.newFloat(fl);
826 // each float has its own counter
827 counters_.newCounter(from_ascii(type), from_ascii(within),
828 docstring(), docstring());
829 // also define sub-float counters
830 docstring const subtype = "sub-" + from_ascii(type);
831 counters_.newCounter(subtype, from_ascii(type),
832 "\\alph{" + subtype + "}", docstring());
839 void TextClass::readCounter(Lexer & lexrc)
845 CT_LABELSTRING_APPENDIX,
849 LexerKeyword counterTags[] = {
851 { "labelstring", CT_LABELSTRING },
852 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
854 { "within", CT_WITHIN }
857 lexrc.pushTable(counterTags);
861 docstring labelstring;
862 docstring labelstring_appendix;
865 while (!getout && lexrc.isOK()) {
866 int le = lexrc.lex();
868 case Lexer::LEX_UNDEF:
869 lexrc.printError("Unknown counter tag `$$Token'");
876 name = lexrc.getDocString();
877 if (counters_.hasCounter(name))
878 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
880 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
884 within = lexrc.getDocString();
885 if (within == "none")
890 labelstring = lexrc.getDocString();
891 labelstring_appendix = labelstring;
893 case CT_LABELSTRING_APPENDIX:
895 labelstring_appendix = lexrc.getDocString();
903 // Here if have a full counter if getout == true
905 counters_.newCounter(name, within,
906 labelstring, labelstring_appendix);
912 bool TextClass::hasLayout(docstring const & n) const
914 docstring const name = n.empty() ? defaultLayoutName() : n;
916 return find_if(layoutlist_.begin(), layoutlist_.end(),
917 LayoutNamesEqual(name))
918 != layoutlist_.end();
923 Layout const & TextClass::operator[](docstring const & name) const
925 LASSERT(!name.empty(), /**/);
928 find_if(begin(), end(), LayoutNamesEqual(name));
931 lyxerr << "We failed to find the layout '" << to_utf8(name)
932 << "' in the layout list. You MUST investigate!"
934 for (const_iterator cit = begin(); cit != end(); ++cit)
935 lyxerr << " " << to_utf8(cit->name()) << endl;
937 // we require the name to exist
938 LASSERT(false, /**/);
945 Layout & TextClass::operator[](docstring const & name)
947 LASSERT(!name.empty(), /**/);
949 iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
952 LYXERR0("We failed to find the layout '" << to_utf8(name)
953 << "' in the layout list. You MUST investigate!");
954 for (const_iterator cit = begin(); cit != end(); ++cit)
955 LYXERR0(" " << to_utf8(cit->name()));
957 // we require the name to exist
958 LASSERT(false, /**/);
965 bool TextClass::deleteLayout(docstring const & name)
967 if (name == defaultLayoutName() || name == emptyLayoutName())
970 LayoutList::iterator it =
971 remove_if(layoutlist_.begin(), layoutlist_.end(),
972 LayoutNamesEqual(name));
974 LayoutList::iterator end = layoutlist_.end();
975 bool const ret = (it != end);
976 layoutlist_.erase(it, end);
981 // Load textclass info if not loaded yet
982 bool TextClass::load(string const & path) const
987 // Read style-file, provided path is searched before the system ones
988 FileName layout_file;
990 layout_file = FileName(addName(path, name_ + ".layout"));
991 if (layout_file.empty() || !layout_file.exists())
992 layout_file = libFileSearch("layouts", name_, "layout");
993 loaded_ = const_cast<TextClass*>(this)->read(layout_file);
996 lyxerr << "Error reading `"
997 << to_utf8(makeDisplayPath(layout_file.absFilename()))
998 << "'\n(Check `" << name_
999 << "')\nCheck your installation and "
1000 "try Options/Reconfigure..." << endl;
1007 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const
1010 InsetLayouts::const_iterator cen = insetlayoutlist_.end();
1011 while (!n.empty()) {
1012 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
1013 if (cit != cen && cit->first == n)
1015 size_t i = n.find(':');
1016 if (i == string::npos)
1020 return empty_insetlayout_;
1024 docstring const & TextClass::defaultLayoutName() const
1026 // This really should come from the actual layout... (Lgb)
1027 return defaultlayout_;
1031 Layout const & TextClass::defaultLayout() const
1033 return operator[](defaultLayoutName());
1037 bool TextClass::isDefaultLayout(Layout const & lay) const
1039 return lay.name() == defaultLayoutName();
1043 bool TextClass::isEmptyLayout(Layout const & lay) const
1045 return lay.name() == emptyLayoutName();
1049 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1051 DocumentClass * dc = new DocumentClass(baseClass);
1052 tc_list_.push_back(dc);
1053 return *tc_list_.back();
1057 DocumentClassBundle & DocumentClassBundle::get()
1059 static DocumentClassBundle singleton;
1064 DocumentClass::DocumentClass(LayoutFile const & tc)
1069 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1071 LayoutList::const_iterator it = layoutlist_.begin();
1072 LayoutList::const_iterator end = layoutlist_.end();
1073 for (; it != end; ++it)
1074 if (it->latexname() == lay)
1080 bool DocumentClass::provides(string const & p) const
1082 return provides_.find(p) != provides_.end();
1086 bool DocumentClass::hasTocLevels() const
1088 return min_toclevel_ != Layout::NOT_IN_TOC;
1092 ostream & operator<<(ostream & os, PageSides p)