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