]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
Paragraph:
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "LayoutFile.h"
20 #include "Color.h"
21 #include "Counters.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "Layout.h"
25 #include "Lexer.h"
26 #include "Font.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/lassert.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"
38
39 #include <algorithm>
40 #include <fstream>
41 #include <sstream>
42
43 using namespace std;
44 using namespace lyx::support;
45
46 namespace lyx {
47
48 namespace {
49
50 class LayoutNamesEqual : public unary_function<Layout, bool> {
51 public:
52         LayoutNamesEqual(docstring const & name)
53                 : name_(name)
54         {}
55         bool operator()(Layout const & c) const
56         {
57                 return c.name() == name_;
58         }
59 private:
60         docstring name_;
61 };
62
63
64 int const FORMAT = 10;
65
66
67 bool layout2layout(FileName const & filename, FileName const & tempfile)
68 {
69         FileName const script = libFileSearch("scripts", "layout2layout.py");
70         if (script.empty()) {
71                 LYXERR0("Could not find layout conversion "
72                           "script layout2layout.py.");
73                 return false;
74         }
75
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();
81
82         LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
83
84         cmd_ret const ret = runCommand(command_str);
85         if (ret.first != 0) {
86                 LYXERR0("Could not run layout conversion script layout2layout.py.");
87                 return false;
88         }
89         return true;
90 }
91
92
93 std::string translateRT(TextClass::ReadType rt) 
94 {
95         switch (rt) {
96         case TextClass::BASECLASS:
97                 return "textclass";
98         case TextClass::MERGE:
99                 return "input file";
100         case TextClass::MODULE:
101                 return "module file";
102         case TextClass::VALIDATION:
103                 return "validation";
104         }
105         // shutup warning
106         return string();
107 }
108
109 } // namespace anon
110
111
112 // This string should not be translated here, 
113 // because it is a layout identifier.
114 docstring const TextClass::plain_layout_ = from_ascii("Plain Layout");
115
116
117 InsetLayout DocumentClass::plain_insetlayout_;
118
119
120 /////////////////////////////////////////////////////////////////////////
121 //
122 // TextClass
123 //
124 /////////////////////////////////////////////////////////////////////////
125
126 TextClass::TextClass()
127 {
128         outputType_ = LATEX;
129         columns_ = 1;
130         sides_ = OneSide;
131         secnumdepth_ = 3;
132         tocdepth_ = 3;
133         pagestyle_ = "default";
134         defaultfont_ = sane_font;
135         opt_fontsize_ = "10|11|12";
136         opt_pagestyle_ = "empty|plain|headings|fancy";
137         titletype_ = TITLE_COMMAND_AFTER;
138         titlename_ = "maketitle";
139         loaded_ = false;
140         _("Plain Layout"); // a hack to make this translatable
141 }
142
143
144 bool TextClass::readStyle(Lexer & lexrc, Layout & lay) const
145 {
146         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
147         if (!lay.read(lexrc, *this)) {
148                 LYXERR0("Error parsing style `" << to_utf8(lay.name()) << '\'');
149                 return false;
150         }
151         // Resolve fonts
152         lay.resfont = lay.font;
153         lay.resfont.realize(defaultfont_);
154         lay.reslabelfont = lay.labelfont;
155         lay.reslabelfont.realize(defaultfont_);
156         return true; // no errors
157 }
158
159
160 enum TextClassTags {
161         TC_OUTPUTTYPE = 1,
162         TC_INPUT,
163         TC_STYLE,
164         TC_DEFAULTSTYLE,
165         TC_INSETLAYOUT,
166         TC_NOSTYLE,
167         TC_COLUMNS,
168         TC_SIDES,
169         TC_PAGESTYLE,
170         TC_DEFAULTFONT,
171         TC_SECNUMDEPTH,
172         TC_TOCDEPTH,
173         TC_CLASSOPTIONS,
174         TC_PREAMBLE,
175         TC_PROVIDES,
176         TC_REQUIRES,
177         TC_LEFTMARGIN,
178         TC_RIGHTMARGIN,
179         TC_FLOAT,
180         TC_COUNTER,
181         TC_NOFLOAT,
182         TC_TITLELATEXNAME,
183         TC_TITLELATEXTYPE,
184         TC_FORMAT,
185         TC_ADDTOPREAMBLE,
186         TC_USEMODULE
187 };
188
189
190 namespace {
191
192         LexerKeyword textClassTags[] = {
193                 { "addtopreamble",   TC_ADDTOPREAMBLE },
194                 { "classoptions",    TC_CLASSOPTIONS },
195                 { "columns",         TC_COLUMNS },
196                 { "counter",         TC_COUNTER },
197                 { "defaultfont",     TC_DEFAULTFONT },
198                 { "defaultstyle",    TC_DEFAULTSTYLE },
199                 { "float",           TC_FLOAT },
200                 { "format",          TC_FORMAT },
201                 { "input",           TC_INPUT },
202                 { "insetlayout",     TC_INSETLAYOUT },
203                 { "leftmargin",      TC_LEFTMARGIN },
204                 { "nofloat",         TC_NOFLOAT },
205                 { "nostyle",         TC_NOSTYLE },
206                 { "outputtype",      TC_OUTPUTTYPE },
207                 { "pagestyle",       TC_PAGESTYLE },
208                 { "preamble",        TC_PREAMBLE },
209                 { "provides",        TC_PROVIDES },
210                 { "requires",        TC_REQUIRES },
211                 { "rightmargin",     TC_RIGHTMARGIN },
212                 { "secnumdepth",     TC_SECNUMDEPTH },
213                 { "sides",           TC_SIDES },
214                 { "style",           TC_STYLE },
215                 { "titlelatexname",  TC_TITLELATEXNAME },
216                 { "titlelatextype",  TC_TITLELATEXTYPE },
217                 { "tocdepth",        TC_TOCDEPTH },
218                 { "usemodule",       TC_USEMODULE }
219         };
220         
221 } //namespace anon
222
223
224 bool TextClass::convertLayoutFormat(support::FileName const & filename, ReadType rt)
225 {
226         LYXERR(Debug::TCLASS, "Converting layout file to " << FORMAT);
227         FileName const tempfile = FileName::tempName("convert_layout");
228         bool success = layout2layout(filename, tempfile);
229         if (success)
230                 success = read(tempfile, rt);
231         tempfile.removeFile();
232         return success;
233 }
234
235 bool TextClass::read(FileName const & filename, ReadType rt)
236 {
237         if (!filename.isReadableFile()) {
238                 lyxerr << "Cannot read layout file `" << filename << "'."
239                        << endl;
240                 return false;
241         }
242
243         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
244                 to_utf8(makeDisplayPath(filename.absFilename())));
245
246         // Define the plain layout used in table cells, ert, etc. Note that 
247         // we do this before loading any layout file, so that classes can 
248         // override features of this layout if they should choose to do so.
249         if (rt == BASECLASS && !hasLayout(plain_layout_))
250                 layoutlist_.push_back(createBasicLayout(plain_layout_));
251
252         Lexer lexrc(textClassTags);
253         lexrc.setFile(filename);
254         ReturnValues retval = read(lexrc, rt);
255         
256         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
257                         to_utf8(makeDisplayPath(filename.absFilename())));
258         
259         if (retval != FORMAT_MISMATCH) 
260                 return retval == OK;
261         
262         bool const worx = convertLayoutFormat(filename, rt);
263         if (!worx) {
264                 LYXERR0 ("Unable to convert " << filename << 
265                         " to format " << FORMAT);
266                 return false;
267         }
268         return true;
269 }
270
271
272 bool TextClass::validate(std::string const & str)
273 {
274         TextClass tc;
275         return tc.read(str, VALIDATION);
276 }
277
278
279 bool TextClass::read(std::string const & str, ReadType rt) 
280 {
281         Lexer lexrc(textClassTags);
282         istringstream is(str);
283         lexrc.setStream(is);
284         ReturnValues retval = read(lexrc, rt);
285
286         if (retval != FORMAT_MISMATCH) 
287                 return retval == OK;
288
289         // write the layout string to a temporary file
290         FileName const tempfile = FileName::tempName("TextClass_read");
291         ofstream os(tempfile.toFilesystemEncoding().c_str());
292         if (!os) {
293                 LYXERR0("Unable to create temporary file");
294                 return false;
295         }
296         os << str;
297         os.close();
298
299         // now try to convert it
300         bool const worx = convertLayoutFormat(tempfile, rt);
301         if (!worx) {
302                 LYXERR0("Unable to convert internal layout information to format " 
303                         << FORMAT);
304         }
305         tempfile.removeFile();
306         return worx;
307 }
308
309
310 // Reads a textclass structure from file.
311 TextClass::ReturnValues TextClass::read(Lexer & lexrc, ReadType rt) 
312 {
313         bool error = !lexrc.isOK();
314
315         // Format of files before the 'Format' tag was introduced
316         int format = 1;
317
318         // parsing
319         while (lexrc.isOK() && !error) {
320                 int le = lexrc.lex();
321
322                 switch (le) {
323                 case Lexer::LEX_FEOF:
324                         continue;
325
326                 case Lexer::LEX_UNDEF:
327                         lexrc.printError("Unknown TextClass tag `$$Token'");
328                         error = true;
329                         continue;
330
331                 default:
332                         break;
333                 }
334
335                 switch (static_cast<TextClassTags>(le)) {
336
337                 case TC_FORMAT:
338                         if (lexrc.next())
339                                 format = lexrc.getInteger();
340                         break;
341
342                 case TC_OUTPUTTYPE:   // output type definition
343                         readOutputType(lexrc);
344                         break;
345
346                 case TC_INPUT: // Include file
347                         if (lexrc.next()) {
348                                 string const inc = lexrc.getString();
349                                 FileName tmp = libFileSearch("layouts", inc,
350                                                             "layout");
351
352                                 if (tmp.empty()) {
353                                         lexrc.printError("Could not find input file: " + inc);
354                                         error = true;
355                                 } else if (!read(tmp, MERGE)) {
356                                         lexrc.printError("Error reading input"
357                                                          "file: " + tmp.absFilename());
358                                         error = true;
359                                 }
360                         }
361                         break;
362
363                 case TC_DEFAULTSTYLE:
364                         if (lexrc.next()) {
365                                 docstring const name = from_utf8(subst(lexrc.getString(),
366                                                           '_', ' '));
367                                 defaultlayout_ = name;
368                         }
369                         break;
370
371                 case TC_STYLE:
372                         if (lexrc.next()) {
373                                 docstring const name = from_utf8(subst(lexrc.getString(),
374                                                     '_', ' '));
375                                 if (name.empty()) {
376                                         string s = "Could not read name for style: `$$Token' "
377                                                 + lexrc.getString() + " is probably not valid UTF-8!";
378                                         lexrc.printError(s.c_str());
379                                         Layout lay;
380                                         // Since we couldn't read the name, we just scan the rest
381                                         // of the style and discard it.
382                                         error = !readStyle(lexrc, lay);
383                                 } else if (hasLayout(name)) {
384                                         Layout & lay = operator[](name);
385                                         error = !readStyle(lexrc, lay);
386                                 } else {
387                                         Layout layout;
388                                         layout.setName(name);
389                                         error = !readStyle(lexrc, layout);
390                                         if (!error)
391                                                 layoutlist_.push_back(layout);
392
393                                         if (defaultlayout_.empty()) {
394                                                 // We do not have a default layout yet, so we choose
395                                                 // the first layout we encounter.
396                                                 defaultlayout_ = name;
397                                         }
398                                 }
399                         }
400                         else {
401                                 lexrc.printError("No name given for style: `$$Token'.");
402                                 error = true;
403                         }
404                         break;
405
406                 case TC_NOSTYLE:
407                         if (lexrc.next()) {
408                                 docstring const style = from_utf8(subst(lexrc.getString(),
409                                                      '_', ' '));
410                                 if (!deleteLayout(style))
411                                         lyxerr << "Cannot delete style `"
412                                                << to_utf8(style) << '\'' << endl;
413                         }
414                         break;
415
416                 case TC_COLUMNS:
417                         if (lexrc.next())
418                                 columns_ = lexrc.getInteger();
419                         break;
420
421                 case TC_SIDES:
422                         if (lexrc.next()) {
423                                 switch (lexrc.getInteger()) {
424                                 case 1: sides_ = OneSide; break;
425                                 case 2: sides_ = TwoSides; break;
426                                 default:
427                                         lyxerr << "Impossible number of page"
428                                                 " sides, setting to one."
429                                                << endl;
430                                         sides_ = OneSide;
431                                         break;
432                                 }
433                         }
434                         break;
435
436                 case TC_PAGESTYLE:
437                         lexrc.next();
438                         pagestyle_ = rtrim(lexrc.getString());
439                         break;
440
441                 case TC_DEFAULTFONT:
442                         defaultfont_ = lyxRead(lexrc);
443                         if (!defaultfont_.resolved()) {
444                                 lexrc.printError("Warning: defaultfont should "
445                                                  "be fully instantiated!");
446                                 defaultfont_.realize(sane_font);
447                         }
448                         break;
449
450                 case TC_SECNUMDEPTH:
451                         lexrc.next();
452                         secnumdepth_ = lexrc.getInteger();
453                         break;
454
455                 case TC_TOCDEPTH:
456                         lexrc.next();
457                         tocdepth_ = lexrc.getInteger();
458                         break;
459
460                 // First step to support options
461                 case TC_CLASSOPTIONS:
462                         readClassOptions(lexrc);
463                         break;
464
465                 case TC_PREAMBLE:
466                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
467                         break;
468
469                 case TC_ADDTOPREAMBLE:
470                         preamble_ += from_utf8(lexrc.getLongString("EndPreamble"));
471                         break;
472
473                 case TC_PROVIDES: {
474                         lexrc.next();
475                         string const feature = lexrc.getString();
476                         lexrc.next();
477                         if (lexrc.getInteger())
478                                 provides_.insert(feature);
479                         else
480                                 provides_.erase(feature);
481                         break;
482                 }
483
484                 case TC_REQUIRES: {
485                         lexrc.eatLine();
486                         vector<string> const req 
487                                 = getVectorFromString(lexrc.getString());
488                         requires_.insert(req.begin(), req.end());
489                         break;
490                 }
491
492                 case TC_USEMODULE: {
493                         lexrc.next();
494                         string const module = lexrc.getString();
495                         if (find(usemod_.begin(), usemod_.end(), module) == usemod_.end())
496                                 usemod_.push_back(module);
497                         break;
498                 }
499
500                 case TC_LEFTMARGIN:     // left margin type
501                         if (lexrc.next())
502                                 leftmargin_ = lexrc.getDocString();
503                         break;
504
505                 case TC_RIGHTMARGIN:    // right margin type
506                         if (lexrc.next())
507                                 rightmargin_ = lexrc.getDocString();
508                         break;
509
510                 case TC_INSETLAYOUT:
511                         if (lexrc.next()) {
512                                 InsetLayout il;
513                                 if (il.read(lexrc, *this))
514                                         insetlayoutlist_[il.name()] = il;
515                                 // else there was an error, so forget it
516                         }
517                         break;
518
519                 case TC_FLOAT:
520                         readFloat(lexrc);
521                         break;
522
523                 case TC_COUNTER:
524                         if (lexrc.next()) {
525                                 docstring const name = lexrc.getDocString();
526                                 if (name.empty()) {
527                                         string s = "Could not read name for counter: `$$Token' "
528                                                         + lexrc.getString() + " is probably not valid UTF-8!";
529                                         lexrc.printError(s.c_str());
530                                         Counter c;
531                                         // Since we couldn't read the name, we just scan the rest
532                                         // and discard it.
533                                         c.read(lexrc);
534                                 } else
535                                         error = !counters_.read(lexrc, name);
536                         }
537                         else {
538                                 lexrc.printError("No name given for style: `$$Token'.");
539                                 error = true;
540                         }
541                         break;
542
543                 case TC_TITLELATEXTYPE:
544                         readTitleType(lexrc);
545                         break;
546
547                 case TC_TITLELATEXNAME:
548                         if (lexrc.next())
549                                 titlename_ = lexrc.getString();
550                         break;
551
552                 case TC_NOFLOAT:
553                         if (lexrc.next()) {
554                                 string const nofloat = lexrc.getString();
555                                 floatlist_.erase(nofloat);
556                         }
557                         break;
558                 } // end of switch
559
560                 //Note that this is triggered the first time through the loop unless
561                 //we hit a format tag.
562                 if (format != FORMAT)
563                         break;
564         }
565
566         if (format != FORMAT)
567                 return FORMAT_MISMATCH;
568
569         if (rt != BASECLASS) 
570                 return (error ? ERROR : OK);
571
572         if (defaultlayout_.empty()) {
573                 LYXERR0("Error: Textclass '" << name_
574                                                 << "' is missing a defaultstyle.");
575                 error = true;
576         }
577                 
578         // Try to erase "stdinsets" from the provides_ set. 
579         // The
580         //   Provides stdinsets 1
581         // declaration simply tells us that the standard insets have been
582         // defined. (It's found in stdinsets.inc but could also be used in
583         // user-defined files.) There isn't really any such package. So we
584         // might as well go ahead and erase it.
585         // If we do not succeed, then it was not there, which means that
586         // the textclass did not provide the definitions of the standard
587         // insets. So we need to try to load them.
588         int erased = provides_.erase("stdinsets");
589         if (!erased) {
590                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
591
592                 if (tmp.empty()) {
593                         throw ExceptionMessage(WarningException, _("Missing File"),
594                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
595                         error = true;
596                 } else if (!read(tmp, MERGE)) {
597                         throw ExceptionMessage(WarningException, _("Corrupt File"),
598                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
599                         error = true;
600                 }
601         }
602
603         min_toclevel_ = Layout::NOT_IN_TOC;
604         max_toclevel_ = Layout::NOT_IN_TOC;
605         const_iterator lit = begin();
606         const_iterator len = end();
607         for (; lit != len; ++lit) {
608                 int const toclevel = lit->toclevel;
609                 if (toclevel != Layout::NOT_IN_TOC) {
610                         if (min_toclevel_ == Layout::NOT_IN_TOC)
611                                 min_toclevel_ = toclevel;
612                         else
613                                 min_toclevel_ = min(min_toclevel_, toclevel);
614                         max_toclevel_ = max(max_toclevel_, toclevel);
615                 }
616         }
617         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
618                 << ", maximum is " << max_toclevel_);
619
620         return (error ? ERROR : OK);
621 }
622
623
624 void TextClass::readTitleType(Lexer & lexrc)
625 {
626         LexerKeyword titleTypeTags[] = {
627                 { "commandafter", TITLE_COMMAND_AFTER },
628                 { "environment",  TITLE_ENVIRONMENT }
629         };
630
631         PushPopHelper pph(lexrc, titleTypeTags);
632
633         int le = lexrc.lex();
634         switch (le) {
635         case Lexer::LEX_UNDEF:
636                 lexrc.printError("Unknown output type `$$Token'");
637                 break;
638         case TITLE_COMMAND_AFTER:
639         case TITLE_ENVIRONMENT:
640                 titletype_ = static_cast<TitleLatexType>(le);
641                 break;
642         default:
643                 LYXERR0("Unhandled value " << le << " in TextClass::readTitleType.");
644                 break;
645         }
646 }
647
648
649 void TextClass::readOutputType(Lexer & lexrc)
650 {
651         LexerKeyword outputTypeTags[] = {
652                 { "docbook",  DOCBOOK },
653                 { "latex",    LATEX },
654                 { "literate", LITERATE }
655         };
656
657         PushPopHelper pph(lexrc, outputTypeTags);
658
659         int le = lexrc.lex();
660         switch (le) {
661         case Lexer::LEX_UNDEF:
662                 lexrc.printError("Unknown output type `$$Token'");
663                 return;
664         case LATEX:
665         case DOCBOOK:
666         case LITERATE:
667                 outputType_ = static_cast<OutputType>(le);
668                 break;
669         default:
670                 LYXERR0("Unhandled value " << le);
671                 break;
672         }
673 }
674
675
676 void TextClass::readClassOptions(Lexer & lexrc)
677 {
678         enum {
679                 CO_FONTSIZE = 1,
680                 CO_PAGESTYLE,
681                 CO_OTHER,
682                 CO_HEADER,
683                 CO_END
684         };
685
686         LexerKeyword classOptionsTags[] = {
687                 {"end",       CO_END },
688                 {"fontsize",  CO_FONTSIZE },
689                 {"header",    CO_HEADER },
690                 {"other",     CO_OTHER },
691                 {"pagestyle", CO_PAGESTYLE }
692         };
693
694         lexrc.pushTable(classOptionsTags);
695         bool getout = false;
696         while (!getout && lexrc.isOK()) {
697                 int le = lexrc.lex();
698                 switch (le) {
699                 case Lexer::LEX_UNDEF:
700                         lexrc.printError("Unknown ClassOption tag `$$Token'");
701                         continue;
702                 default: break;
703                 }
704                 switch (le) {
705                 case CO_FONTSIZE:
706                         lexrc.next();
707                         opt_fontsize_ = rtrim(lexrc.getString());
708                         break;
709                 case CO_PAGESTYLE:
710                         lexrc.next();
711                         opt_pagestyle_ = rtrim(lexrc.getString());
712                         break;
713                 case CO_OTHER:
714                         lexrc.next();
715                         options_ = lexrc.getString();
716                         break;
717                 case CO_HEADER:
718                         lexrc.next();
719                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
720                         break;
721                 case CO_END:
722                         getout = true;
723                         break;
724                 }
725         }
726         lexrc.popTable();
727 }
728
729
730 void TextClass::readFloat(Lexer & lexrc)
731 {
732         enum {
733                 FT_TYPE = 1,
734                 FT_NAME,
735                 FT_PLACEMENT,
736                 FT_EXT,
737                 FT_WITHIN,
738                 FT_STYLE,
739                 FT_LISTNAME,
740                 FT_BUILTIN,
741                 FT_END
742         };
743
744         LexerKeyword floatTags[] = {
745                 { "end", FT_END },
746                 { "extension", FT_EXT },
747                 { "guiname", FT_NAME },
748                 { "latexbuiltin", FT_BUILTIN },
749                 { "listname", FT_LISTNAME },
750                 { "numberwithin", FT_WITHIN },
751                 { "placement", FT_PLACEMENT },
752                 { "style", FT_STYLE },
753                 { "type", FT_TYPE }
754         };
755
756         lexrc.pushTable(floatTags);
757
758         string type;
759         string placement;
760         string ext;
761         string within;
762         string style;
763         string name;
764         string listName;
765         bool builtin = false;
766
767         bool getout = false;
768         while (!getout && lexrc.isOK()) {
769                 int le = lexrc.lex();
770                 switch (le) {
771                 case Lexer::LEX_UNDEF:
772                         lexrc.printError("Unknown float tag `$$Token'");
773                         continue;
774                 default: break;
775                 }
776                 switch (le) {
777                 case FT_TYPE:
778                         lexrc.next();
779                         type = lexrc.getString();
780                         if (floatlist_.typeExist(type)) {
781                                 Floating const & fl = floatlist_.getType(type);
782                                 placement = fl.placement();
783                                 ext = fl.ext();
784                                 within = fl.within();
785                                 style = fl.style();
786                                 name = fl.name();
787                                 listName = fl.listName();
788                                 builtin = fl.builtin();
789                         } 
790                         break;
791                 case FT_NAME:
792                         lexrc.next();
793                         name = lexrc.getString();
794                         break;
795                 case FT_PLACEMENT:
796                         lexrc.next();
797                         placement = lexrc.getString();
798                         break;
799                 case FT_EXT:
800                         lexrc.next();
801                         ext = lexrc.getString();
802                         break;
803                 case FT_WITHIN:
804                         lexrc.next();
805                         within = lexrc.getString();
806                         if (within == "none")
807                                 within.erase();
808                         break;
809                 case FT_STYLE:
810                         lexrc.next();
811                         style = lexrc.getString();
812                         break;
813                 case FT_LISTNAME:
814                         lexrc.next();
815                         listName = lexrc.getString();
816                         break;
817                 case FT_BUILTIN:
818                         lexrc.next();
819                         builtin = lexrc.getBool();
820                         break;
821                 case FT_END:
822                         getout = true;
823                         break;
824                 }
825         }
826
827         // Here if have a full float if getout == true
828         if (getout) {
829                 Floating fl(type, placement, ext, within,
830                             style, name, listName, builtin);
831                 floatlist_.newFloat(fl);
832                 // each float has its own counter
833                 counters_.newCounter(from_ascii(type), from_ascii(within),
834                                       docstring(), docstring());
835                 // also define sub-float counters
836                 docstring const subtype = "sub-" + from_ascii(type);
837                 counters_.newCounter(subtype, from_ascii(type),
838                                       "\\alph{" + subtype + "}", docstring());
839         }
840
841         lexrc.popTable();
842 }
843
844
845 bool TextClass::hasLayout(docstring const & n) const
846 {
847         docstring const name = n.empty() ? defaultLayoutName() : n;
848
849         return find_if(layoutlist_.begin(), layoutlist_.end(),
850                        LayoutNamesEqual(name))
851                 != layoutlist_.end();
852 }
853
854
855 Layout const & TextClass::operator[](docstring const & name) const
856 {
857         LASSERT(!name.empty(), /**/);
858
859         const_iterator it = 
860                 find_if(begin(), end(), LayoutNamesEqual(name));
861
862         if (it == end()) {
863                 lyxerr << "We failed to find the layout '" << to_utf8(name)
864                        << "' in the layout list. You MUST investigate!"
865                        << endl;
866                 for (const_iterator cit = begin(); cit != end(); ++cit)
867                         lyxerr  << " " << to_utf8(cit->name()) << endl;
868
869                 // we require the name to exist
870                 LASSERT(false, /**/);
871         }
872
873         return *it;
874 }
875
876
877 Layout & TextClass::operator[](docstring const & name)
878 {
879         LASSERT(!name.empty(), /**/);
880
881         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
882
883         if (it == end()) {
884                 LYXERR0("We failed to find the layout '" << to_utf8(name)
885                        << "' in the layout list. You MUST investigate!");
886                 for (const_iterator cit = begin(); cit != end(); ++cit)
887                         LYXERR0(" " << to_utf8(cit->name()));
888
889                 // we require the name to exist
890                 LASSERT(false, /**/);
891         }
892
893         return *it;
894 }
895
896
897 bool TextClass::deleteLayout(docstring const & name)
898 {
899         if (name == defaultLayoutName() || name == plainLayoutName())
900                 return false;
901
902         LayoutList::iterator it =
903                 remove_if(layoutlist_.begin(), layoutlist_.end(),
904                           LayoutNamesEqual(name));
905
906         LayoutList::iterator end = layoutlist_.end();
907         bool const ret = (it != end);
908         layoutlist_.erase(it, end);
909         return ret;
910 }
911
912
913 // Load textclass info if not loaded yet
914 bool TextClass::load(string const & path) const
915 {
916         if (loaded_)
917                 return true;
918
919         // Read style-file, provided path is searched before the system ones
920         // If path is a file, it is loaded directly.
921         FileName layout_file(path);
922         if (!path.empty() && !layout_file.isReadableFile())
923                 layout_file = FileName(addName(path, name_ + ".layout"));
924         if (layout_file.empty() || !layout_file.exists())
925                 layout_file = libFileSearch("layouts", name_, "layout");
926         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
927
928         if (!loaded_) {
929                 lyxerr << "Error reading `"
930                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
931                        << "'\n(Check `" << name_
932                        << "')\nCheck your installation and "
933                         "try Options/Reconfigure..." << endl;
934         }
935
936         return loaded_;
937 }
938
939
940 void DocumentClass::addLayoutIfNeeded(docstring const & n) const
941 {
942         if (!hasLayout(n))
943                 layoutlist_.push_back(createBasicLayout(n, true));
944 }
945
946
947 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
948 {
949         // FIXME The fix for the InsetLayout part of 4812 would be here:
950         // Add the InsetLayout to the document class if it is not found.
951         docstring n = name;
952         InsetLayouts::const_iterator cen = insetlayoutlist_.end();
953         while (!n.empty()) {
954                 InsetLayouts::const_iterator cit = insetlayoutlist_.lower_bound(n);
955                 if (cit != cen && cit->first == n)
956                         return cit->second;
957                 size_t i = n.find(':');
958                 if (i == string::npos)
959                         break;
960                 n = n.substr(0, i);
961         }
962         return plain_insetlayout_;
963 }
964
965
966 docstring const & TextClass::defaultLayoutName() const
967 {
968         // This really should come from the actual layout... (Lgb)
969         return defaultlayout_;
970 }
971
972
973 Layout const & TextClass::defaultLayout() const
974 {
975         return operator[](defaultLayoutName());
976 }
977
978
979 bool TextClass::isDefaultLayout(Layout const & layout) const 
980 {
981         return layout.name() == defaultLayoutName();
982 }
983
984
985 bool TextClass::isPlainLayout(Layout const & layout) const 
986 {
987         return layout.name() == plainLayoutName();
988 }
989
990
991 Layout TextClass::createBasicLayout(docstring const & name, bool unknown) const
992 {
993         static Layout * defaultLayout = NULL;
994
995         if (defaultLayout) {
996                 defaultLayout->setUnknown(unknown);
997                 defaultLayout->setName(name);
998                 return *defaultLayout;
999         }
1000
1001         static char const * s = "Margin Static\n"
1002                         "LatexType Paragraph\n"
1003                         "LatexName dummy\n"
1004                         "Align Block\n"
1005                         "AlignPossible Left, Right, Center\n"
1006                         "LabelType No_Label\n"
1007                         "End";
1008         istringstream ss(s);
1009         Lexer lex(textClassTags);
1010         lex.setStream(ss);
1011         defaultLayout = new Layout;
1012         defaultLayout->setUnknown(unknown);
1013         defaultLayout->setName(name);
1014         if (!readStyle(lex, *defaultLayout)) {
1015                 // The only way this happens is because the hardcoded layout above
1016                 // is wrong.
1017                 LASSERT(false, /**/);
1018         };
1019         return *defaultLayout;
1020 }
1021
1022 /////////////////////////////////////////////////////////////////////////
1023 //
1024 // DocumentClassBundle
1025 //
1026 /////////////////////////////////////////////////////////////////////////
1027
1028 DocumentClassBundle::~DocumentClassBundle()
1029 {
1030         for (size_t i = 0; i != documentClasses_.size(); ++i)
1031                 delete documentClasses_[i];
1032         documentClasses_.clear();
1033 }
1034
1035 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
1036 {
1037         DocumentClass * dc = new DocumentClass(baseClass);
1038         documentClasses_.push_back(dc);
1039         return *documentClasses_.back();
1040 }
1041
1042
1043 DocumentClassBundle & DocumentClassBundle::get()
1044 {
1045         static DocumentClassBundle singleton; 
1046         return singleton; 
1047 }
1048
1049
1050 /////////////////////////////////////////////////////////////////////////
1051 //
1052 // DocumentClass
1053 //
1054 /////////////////////////////////////////////////////////////////////////
1055
1056 DocumentClass::DocumentClass(LayoutFile const & tc)
1057         : TextClass(tc)
1058 {}
1059
1060
1061 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1062 {
1063         LayoutList::const_iterator it  = layoutlist_.begin();
1064         LayoutList::const_iterator end = layoutlist_.end();
1065         for (; it != end; ++it)
1066                 if (it->latexname() == lay)
1067                         return true;
1068         return false;
1069 }
1070
1071
1072 bool DocumentClass::provides(string const & p) const
1073 {
1074         return provides_.find(p) != provides_.end();
1075 }
1076
1077
1078 bool DocumentClass::hasTocLevels() const
1079 {
1080         return min_toclevel_ != Layout::NOT_IN_TOC;
1081 }
1082
1083
1084 /////////////////////////////////////////////////////////////////////////
1085 //
1086 // PageSides
1087 //
1088 /////////////////////////////////////////////////////////////////////////
1089
1090 ostream & operator<<(ostream & os, PageSides p)
1091 {
1092         switch (p) {
1093         case OneSide:
1094                 os << '1';
1095                 break;
1096         case TwoSides:
1097                 os << '2';
1098                 break;
1099         }
1100         return os;
1101 }
1102
1103
1104 } // namespace lyx