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