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